Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django api endpoint working in postman but returning undefined in the front end after axios get call
I have the following 2 projects to analyze financial data: https://github.com/codyc4321/dividends_ui https://github.com/codyc4321/stocks_backend I have an endpoint like such from django.shortcuts import render from django.http import HttpResponse from django.core import serializers import datetime, json, yfinance def get_current_price(yahoo_obj): info = yahoo_obj.get_info() price = info['currentPrice'] return price def get_all_dividends(yahoo_obj): panda_dividends_obj = yahoo_obj.dividends dividends_dicts = [] for i, v in panda_dividends_obj.iteritems(): dividends_dicts.append({'date': i.to_pydatetime().date(), 'amount': v}) return dividends_dicts def get_current_dividend_yield(price, dividends): """ this doesnt need any dates because current assumes were checking the rate over this past year""" rate = get_yearly_dividend_rate_from_date(dividends, datetime.date.today()) return round((rate / price) * 100, 2) def current_dividend_yield_view(request, ticker): yahoo_stock_obj = yfinance.Ticker(ticker.upper()) price = get_current_price(yahoo_stock_obj) dividends = get_all_dividends(yahoo_stock_obj) current_yield = get_current_dividend_yield(price, dividends) current_yield_object = {'current_yield': current_yield} data = json.dumps(current_yield_object) return HttpResponse(data, content_type='application/json') and path('current_yield/<str:ticker>/', views.current_dividend_yield_view, name='current_yield'), according to postman and my browser the endpoint works as intended my app.js passes the callback to the SearchBar component import React from 'react'; import SearchBar from './SearchBar'; import axios from 'axios'; class App extends React.Component { state = {data: null} onSearchSubmit = async (term) => { const url = 'http://localhost:8000/dividends/current_yield/' + term console.log(url) const response = await axios.get(url, { params: {query: term}, headers: { // Authorization: 'Client-ID *YOUR KEY HERE*' // "Access-Control-Allow-Origin": "*", } }); … -
Python: Making post.file.url unique for image and video files
Ive been working on a social media website where you can upload images and videos and follow other users. I managed to upload and display uploaded files to the website. I used FileField to load the image and video files, but when I implement it in my Template it shows both spaces, because there both using the same source url {{ source.file.url }} models.py class Post(models.Model): title = models.CharField(max_length=150) file = models.FileField(upload_to='uploads/%Y-%m-%d') feeds.html {% if post.file.url %} <video class="video-context" width="500px" height="500px" controls> <source src="{{ post.file.url }}" type="video/mp4"> </video> {% endif %} {% if post.file.url %} <img class="image-context" src="{{ post.file.url }}" type="image/jpg" type="image/jpeg"> {% endif %} heres a sreenshot empty video player over img I tried the if endswith form: {% if file.endswith .mp4 %} <video class="video-context" width="500px" height="500px" controls> <source src="{{ post.file.url }}" type="video/mp4"> </video> {% endif %} {% if file.endswith .jpg/jpeg %} <img class="image-context" src="{{ post.file.url }}"> {% endif %} But it didn't work. How can I just display the file thats uploaded. How can I make the {{ post.file.url }} unique for image and video, so its easier to difference? How is it possible to difference the upload types, but still using FileField? -
Django: Multiple Photos Uploading not connected to user
i've been trying to upload multiple photos to the gallery of a user and i am being able to do so but they are not being connected to the user who is uploading them. images just gets to the specified path but when i see it in admin panel, photos are there, but no user is connected to them. #views.py def images(request): owner = request.user.profile name = request.POST.get('filename') files = request.FILES.getlist('images') for file in files: i = Images.objects.create(image=file,) i.save() return render(request, 'profiles/images.html') #models.py class Images(models.Model): profile = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) f_name = models.CharField(max_length=250, null=True) image = models.ImageField(upload_to='user/') updated = models.DateField(auto_now=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) #forms.py class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Images fields = ('image',) -
How to make a password authentication with QR for a django html form
I have made a password protected page with django and cms wagtail, i need the following cases to happen: If user enters the url normally: page requires him a password through an HTML form, and don't get him access to it until it gives the correct password (Done). If user enters with a QR code: page doesn't require him the password, and get him immediate access to the content page. Models.py: from wagtail.core.models import Page, PageViewRestriction from wagtail.images.edit_handlers import ImageChooserPanel from django.utils.translation import gettext_lazy as _ class ProfilePage(Page): template = 'profile/profile_page.html' def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) return context def save(self, *args, **kwargs): your_page = ProfilePage.objects.all().first() PageViewRestriction.objects.create(page=your_page, restriction_type='password') return super().save(*args, **kwargs) password template (wagtail's default one): <!DOCTYPE HTML> <html> <head> <title>Password required</title> </head> <body> <h1>Password required</h1> <p>You need a password to access this page.</p> <form action="{{ action_url }}" method="POST"> {% csrf_token %} {{ form.non_field_errors }} <div> {{ form.password.errors }} {{ form.password.label_tag }} {{ form.password }} </div> {% for field in form.hidden_fields %} {{ field }} {% endfor %} <input type="submit" value="Continue" /> </form> </body> </html> -
Custom ordering in django rest framework?
I have view: class ContactListView(generics.ListAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializer filter_backends = (filters.SearchFilter,filters.OrderingFilter) ordering_fields = ['name'] search_fields = ('name',) I set ordering by name but name contains First Name and Last Name , I want to set order by Last Name I created : class SurnameOrdering(OrderingFilter): ordering_fields = ['surname'] def get_ordering(self, request, queryset, view): pass but how set this ordering ?? -
How to restrict regular users from accessing admin page?
I would like to allow only admin users to access admin page and raise 404 error if user is not authenticated or is not a staff member. Is there a way to wrap admin view with another function to check if user is admin? -
Django How to pass username in a predefined template
I created a templates for header/footer and imports, if I want to acess the username in my header template I cant do that because it has no views. How can I pass the username to the header template? header_template.py from django import template register = template.Library() @register.inclusion_tag('home/partials/header.html') def header(element): return {'element': element, } Import in Template {% load header_template %} {% header context %} Usage in the template: {% if user.is_authenticated %} <a class="btn btn-primary display-4" href="{% url 'home:profil' %}">Profil</a> {% else %} <a class="btn btn-primary display-4" href="{% url 'home:login' %}">Login</a> {% endif %} Thanks for your help. -
Docker-Compose Django can't connect to DB or Celery
I have everything on one network (it talks to another app in another docker-compose file). But I keep getting this error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (192.168.208.3) and accepting TCP/IP connections on port 5000? When I change my SQL_PORT=5432 (default port that's running in the postgres container) the error above disappears and my app is up, but then it has problems when trying to connect to celery or in shell it says db is not connected. I have to use 5000 cause there is another postgres db on the other app in the second docker-compose setup. I think I'm lost on the internals of networks. I was pretty sure I am suppose to use the exposed port of 5000 for my database. version: "3.9" services: app: build: . command: python manage.py runserver 0.0.0.0:8000 container_name: app environment: - DEBUG=True - PYTHONUNBUFFERED=1 - CELERY_BROKER=redis://broker:6379/0 - CELERY_BACKEND=redis://broker:6379/ - APP_BASIC_AUTH_PASSWORD=adPswd12* - APP_BASIC_AUTH_USER=admin - APP_TOKEN_AUTH=NHEC_UTILITY - VTN_API_URL=vtn_app:8000 - VTN_API_TOKEN=NHECAPP_UTILITY - SQL_PORT=5000 volumes: - .:/code ports: - "9000:8000" networks: - app-web-net depends_on: - db - celery-worker - broker app_test: build: . command: python manage.py test container_name: app_test environment: - DEBUG=True - … -
Django multiple user group design method
I have a project for a staffing service company that has at least four user groups (admin, employers, employees and the owner of the staffing service company). Each of them has the following functions: Admin can do everything. Employer can publish, update, view the job/gag events. (can't delete without admin's permission). Employee can view, confirm/update after finishing the events. Owner is pretty much similar to admin. Perhaps does not have delete permission. BTW, admin and owner could be the same person if it would be simpler. I have read some blogs and some of them mentioned to use AbstractUser subclass, etc. However, I still feel not clear enough. Should I build an app called User which has three or four classes in that model.py in User App? Those four classes would be "Class Admin", "Class Owner", "Class Emoloyee", "Class Employer"? Or how should I implement it? Any advice? Thank you! -
Enum field in MySQL
In MySQL there are several types of data, char, varchar int, boolean as you already know. But it also has the Enum type that in SQL we create the table as follows: CREATE TABLE person( id int..... name varchar(50), and Married Enum(Yes,No) ) My goal is, when I'm creating the models in Django (Python) to be able to create the tables in MySQL I can automatically create this type of field as well. I tried like this: from django.db import models from enum import enum class options(Enum): Yes = "Yes" No = "No" class Customer(models.Model) : name = models.CharField(max_length=200) docto = models.CharField(max_length=14) age = models.IntegerField(default=0) username = models.CharField(max_length=20) password = models.CharField(max_length=20) block = models.CharField( max_length=3, choices=[(tag, tag.value) for tag in options], default= 'No' ) def __str__(self): return self.name Create the field in MySQL creates but creates as VARCHAR(3) and not as enum. Can Django do this? How would it be? I wouldn't like to have to create the tables directly in the database, -
Django Forms Radio Button
I had made a form using django forms and call it to a template but while I select a radio button it won't pick what's the solution ''' html section ''' <div class="form-row p-t-20"> <label class="label label--block">Gender</label> {% for radio in form.Gender %} <div class="p-t-15"> <label class="radio-container"> {{radio}} <input type="radio" name="gender"> <span class="checkmark"></span> </label> </div> ''' forms section ''' Gender = forms.ChoiceField(choices=GenderChoice,widget=forms.RadioSelect(attrs={'class':'form-check form-check-inline'})) -
Django is not creating any fields with users created manually
i've created a eccomerce website. this has a registration page where users creates their user account & then can order anything. if i create a user from admin panel, then everything works perfectly. but if i create a user from front end of my registration page using React js, then that user can't order anything, meaning when i post a data using fetch django doesn't store or create any data for that user. why? what's the issue here? i'm using Rest Api in backend & posting data through fetch to send data. but the fetch fails but not if i use a user which was created from admin panel(./admin). am i doing anything wrong in creating the user data manually at my views??? #my_views from django.shortcuts import redirect from django.contrib.auth.hashers import make_password from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from App.models import * from api.forms import RegisterForm from .serializers import * from django.contrib.auth.models import User class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username # ... return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer @api_view(['GET','POST']) def getRoutes(request): routes = [ '/api/token', '/api/refresh', ] return Response(routes) … -
Errors not showing in Django signup template form
Hi i need help with my code, errors not showing up in my HTML form and i dont know how to debug it or how to understand why the div isnt showing, i tried changing its CSS i tried changing classname i tried everything i just cant get it to show when i put bad inputs. views.py from django.shortcuts import render, redirect from .forms import SignUpForm from django.contrib.auth import login def frontpage(request): return render(request,'core/frontpage.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('frontpage') else: form = SignUpForm() return render(request, 'core/signup.html', {'form': form}) signup.html {% extends 'core/base.html' %} {% block title %} Sign Up | {% endblock %} {% block content %} <div class="main"> <h1>Sign Up</h1> </div> <div class="form-container"> <form method="post" action="." class="sign-up-form"> {% csrf_token %} <p>Fill Form :</p> <div class="form-items"> <label for="username">Username</label> <input type="text" class="label" id="username" name="username" placeholder="Username" > <label for="password">Password</label> <input type="password" class="label" id="password" name="password1" placeholder="Password"> <label for="confirm-password">Confirm Password</label> <input type="password" class="label" id="confirm-password" name="password2" placeholder="Confirm Password"> {% if form.error %} {% for field in form %} {% for error in field.errors %} <div class="error-msg"> <p>{{ error|escape }}</p> </div> {% endfor %} {% endfor %} {% endif %} <div class="form-control-buttons"> <button … -
ImportError: Module 'django.contrib' does not contain a 'Advisor' class. ------- why am I getting this error
Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\mgkco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\apps\config.py", line 225, in create raise ImportError(msg) ImportError: Module 'django.contrib' does not contain a 'Advisor' class. -
How to use django-oauth-toolkit to protect a package's API
I'm developing a web API using "django-scim2" package. As a development requirement, bearer token authentication is required when accessing the django-scim2 API via http. The django-scim2 documentation (https://django-scim2.readthedocs.io/en/latest/) says "This app does not implement authorization and authentication. Such tasks are left for other apps such as Django OAuth Toolkit to implement." And as I check the django-oauth-toolkit docs, I can see how to protect it when you create a function or class, https://django-oauth-toolkit.readthedocs.io/en/2.1.0/views/function_based.html https://django-oauth-toolkit.readthedocs.io/en/2.1.0/views/class_based.html but django-scim2 is loaded from config/urls.py as it is (like below), so I have nothing to do and I don't know how to implement it. [config/urls.py] urlpatterns = [ path('admin/', admin.site.urls), path('scim/v2/', include('django_scim.urls', namespace='scim')), ... I would be grateful if you could give me some good advice. -
How to implement this function?
I have model Contact class Contact(models.Model): name = models.CharField(max_length=255) phone = models.CharField(max_length=255) appearance = models.PositiveIntegerField(default=0) def get_appear(self): self.appearance += 1 where appearance is how match I'm browsing this endpoint my views.py is : class ContactView(generics.RetrieveAPIView): queryset = Contact.objects.all() serializer_class = ContactIdSerializer def retrieve(self, request, *args, **kwargs): instance = self.get_object() instance.get_appear() serializer = self.get_serializer(instance) return Response(serializer.data) serializers.py: class ContactIdSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = ['id', 'name', 'phone', 'address', 'appearance'] Problem is when I go to my id : http://127.0.0.1:8000/api/v1/contacts/3/ every time appearance should increase by 1 , but this value always equals 1 and value of appearance in db always equals 0 -
Django/react Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
I am building a website using django as purely a server and React. I am getting the error Access to XMLHttpRequest at 'http://localhost:8000/dividends/current_yield/hd' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. so far i've tried Redirect is not allowed for a preflight request and "No 'Access-Control-Allow-Origin' header is present on the requested resource" in django I added corsheaders to my installed apps in django, and still no luck my app.js looks like import React from 'react'; import SearchBar from './SearchBar'; import axios from 'axios'; class App extends React.Component { onSearchSubmit(term) { axios.get('http://localhost:8000/dividends/current_yield/hd', { // params: {query: term}, headers: { // Authorization: 'Client-ID *YOUR KEY HERE*' // "Access-Control-Allow-Origin": "*", } }).then(response => { console.log(response.data.results); }); } render() { return ( <div className="ui container" style={{marginTop: '10px'}}> <SearchBar onSubmit={this.onSearchSubmit} /> </div> ) } } export default App; my views looks like def current_dividend_yield_view(request, ticker): yahoo_stock_obj = yfinance.Ticker(ticker.upper()) price = get_current_price(yahoo_stock_obj) dividends = get_all_dividends(yahoo_stock_obj) current_yield = get_current_dividend_yield(price, dividends) current_yield_object = {'current_yield': current_yield} data = json.dumps(current_yield_object) return HttpResponse(data, content_type='application/json') my settings.py ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dividends_info.apps.DividendsInfoConfig', 'corsheaders', ] MIDDLEWARE = [ … -
How to import parent template except for its overriden content in django templates?
I'm trying to extend two nested blocks from a parent template in a child template. It goes like this : parent.html {% block parentBlock %} <span> Foo </span> {% block rowBlock %} <button ...> Button here </button> <button ...> Another button here </button> {% endblock rowBlock %} <div> Some other content </div> {% endblock parentBlock %} child.html {% extends 'parent.html' %} {% block parentBlock %} {{ block.super }} # --> See note n°1 below {% block rowBlock %} {{ block.super }} <button ...> A third button that extends the 2 others </button> {% endblock rowBlock %} <div> Content that extends parentBlock from parent.html </div> {% endblock parentBlock %} Note n° 1: Problem is that the child's block.super on parentBlock marked as Note 1 will do a super that includes the new rowBlock and appends the new one one more. Result is like this : <span> Foo </span> <button ...> Button here </button> <button ...> Another button here </button> <button ...> A third button that extends the 2 others </button> <button ...> Button here </button> <button ...> Another button here </button> <button ...> A third button that extends the 2 others </button> <div> Some other content </div> <div> Content that extends … -
Production deployable, scalable and managed solution from Heroku
I explored most of the options available in Heroku and none of them has a feasible and managed plan for Django based eCommerce web application. We basically don't want to manage the infrastructure and configurations, but would like to focus on coding and deploy it on a managed solution that is feasible to us. Currently we have the following software stack on a development server and we would like to find a Heroku managed solution, yet scalable and production deployable. Linux OS Postgres Python 3.10 Django latest ( with and without REST APIs) Vue.js Gunicorn Nginx Let's Encrypt or any SSL Redis Celery Github Jenkins CI/CD (the code is automatically deployed on the development server by running a Jenkins job) Integrated API: Stripe, Twilio, Google and etc. Best regards -
Django template forloop values in jquery
I am using Django for a question and answer project. I have a template with multiple answers and, for each answer, I have a "Comment" button to toggle a textarea where I can add a comment to the answer itself. My problem is, I can just toggle the first "comment" button, because jquery gets the first item as unique id. I post some code to be more clear: template {% for answer in answers %} <div class="col-1"> <div style="text-align: center"> <a title="Dai un voto positivo" href="" class="btn btn-lg"><i class="fas fa-arrow-circle-up"></i></a> <br> <span>{{ answer.count_all_the_votes }}</span> <br> <a title="Dai un voto negativo" href="" class="btn btn-lg"><i class="fas fa-arrow-circle-down"></i></a> <br> {% if request.user == question.post_owner %} <a title="Accetta questa risposta come corretta" href="" class="btn btn-lg"><i class="fas fa-check"></i></a> {% endif %} </div> </div> <div class="col-11"> {{ answer.body|safe }} <br> <div class="mt-3"> {% if request.user == answer.answer_owner %} <a href="">Modifica</a> {% endif %} &nbsp;&nbsp;&nbsp; <a href="">Segnala</a> </div> <hr> {% for comment in answer_comments %} {% if comment.answer.id == answer.id %} <small>{{ comment.comment }} - <a href="">{{ comment.commented_by }}</a> {{ comment.created_at }}</small> <hr> {% endif %} {% endfor %} <button class="btn btn-link" id="ans_show_button{{answer.id}}">Commenta</button> <input type="hidden" name="" value="{{answer.id}}"> <div class="col-6"> <form action="{% url 'questions:add_answer_comment' pk=answer.id %}" method="post"> {% … -
What is the difference between timezone.now and db.models.functions.Now?
Can anyone explain the difference between 'django.db.models.functions.Now' and 'django.utils.timezone.now'? For example, am I correct that functions.Now() returns the system time without timezone stamp, and timezone.now() would return UTC timestamp? When I use print(timezone.now()) I get the expected timestamp however when I print(functions.Now()) I get a blank string. Why is this? In what circumstances is it appropriate to use one method over the other? -
circular import error in django rest framework
I have two custom modules in the root project folder: root/setting.py root/utils/custom_exception.py root/custom_authentication.py I am importing from rest_framework import exception_handler, from rest_framework.exceptions import APIException in the custom_exception.py module. When I import CustomExceptionClass from custom_exception.py in custom_authentication.py, I get a cyclical import error: ImportError: cannot import name 'exception_handler' from partially initialized module 'rest_framework.views' (most likely due to a circular import) However when I import the same exception class inside the authenticate method , the error is gone. Does anyone know why I am not able to import globally? -
Django large file uploads to s3 on heroku
For the love of god can we get a solution for uploading large files to Amazon s3 bucket on heroku? I have been through everything on the net and no working solutions or clear documentation. Meanwhile YouTube uploading hour long HD videos!!!! Please only people with experience or success in uploading large 20 minute videos to there app answer. Don’t want people with no experience references other broken answers. By the way my website is www.theraplounge.co/ and we can’t get large file uploaded for nonthing. (Boto3, these s3-direct widgets) you name it. -
Returning a Crispy Form as response to ajax request
i am trying to fill a form with data via ajax request. The is my attempt so far: view.py: def ajaxGetData(request): pnr=int(request.GET.get('pnr',None)) instance=User.objects.get(pnr=pnr) form=User_Form(instance=instance,prefix="Userdata") return HttpResponse(form.as_p()) Ajax Code: $.ajax({ url: '{%url 'ajaxGetData'%}', type: "get", data: { 'pnr': pnr, }, success: function (data) { if (data) { $('#Userdata-Content').html(data); } } }); It does work, but the form is not rendered with crispy-forms. Is there some code like return HttpResponse(form.as_crispy()) That would return a crispy form? PS: I am quite new to Django and developing websites in general. I want to do a website where you can select a user from a list at the side of the page and then edit a whole bunch of data about him. From what i read doing a one-page-solution was the way to go for that. Would be quite thankful if someone can give me a hint if this is the right way to go about it. Greetings! -
Django Rest Framework - One serailizer for API and drf-spectacular
I have a serializer for DRF, and drf-spectacular. My serializer works that i expect but in GUI don't present currectly. So i need to have tho diffrents serializer one for schema and second for endpoint. But i wanna use one, how to fix this ? My serializer: class GetConversionCasesSerializer(serializers.Serializer): conversionId = serializers.SerializerMethodField() cases = serializers.SerializerMethodField() def get_cases(self, obj): serializer = ResultDataSerializer(ResultData.objects.filter(conversion=obj), many=True) data = serializer.data return data def get_conversionId(self, obj): return obj.id Schema serializer: class GetConversionCasesSerializerSchema(serializers.Serializer): conversionId = serializers.IntegerField() cases = serializers.ListSerializer(child=ResultDataSerializer()) Api endpoint: @extend_schema(request=None, responses=GetConversionCasesSerializerSchema()) def get(self, *args, **kwargs): if self.request.version == "v1": conversion_id = self.kwargs.get('conversion_id') instance = Conversion.objects.get(id=conversion_id) serializer = GetConversionCasesSerializer(instance) serializer.data['c1'] = 'test' return Response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) When i use to show schema normal selialiser i have: in schema serializer: How to fix first serializer and have one for schema and get method ?