Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Errors in Importing assets folder with static url in React parcel project
I am trying to serverside render a react page using Django. The server-side rendering is working fine for normal react components. The project is using parcel to auto-build javaScript files so that Django could render them. This is the command I am using to compile react to Js. "scripts": { "watch": "parcel watch src/index.tsx --public-url /assets/" } I am new to the parcel, So sorry for the poor framing of the problem and/or any wrong terminology. The problem comes whenever I try to import an assets component in my assets folder into my react components. The import statement in my react code is working fine but I am getting an error in the import statements of the assets folder telling the file path for import is wrong. Here is the below screenshot of the issue. enter image description here @parcel/core: Failed to resolve 'assets/theme/base/typography' from './src/assets/theme/index.js' C:\profitional\BRAVO\Server\assets\src\assets\theme\index.js:23:24 22 | import breakpoints from "assets/theme/base/breakpoints"; > 23 | import typography from "assets/theme/base/typography"; > | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 24 | import boxShadows from "assets/theme/base/boxShadows"; 25 | import borders from "assets/theme/base/borders"; Done in 689.72s. C:\profitional\BRAVO\Server\assets>yarn parcel watch src/index.tsx yarn run v1.22.19 $ C:\profitional\BRAVO\Server\assets\node_modules\.bin\parcel watch src/index.tsx × Build failed. @parcel/core: Failed to resolve 'assets/theme/base/breakpoints' from './src/assets/theme/index.js' C:\profitional\BRAVO\Server\assets\src\assets\theme\index.js:22:25 … -
Django - model images are not loading
I add a ImageField model in my models and save the photos in my project folder. I send the objects to my template but I can't load the images. My app name is observatory and I can have other parts of models except images. Here is my code : Models.py : Class Observatorys (models.Model): ... photo = models.ImageField(upload_to = "photos/%Y/%m/%d") Views.py : From .models import Observatorys def Observatorys(request): Observatorys = observatory.objects.all() context= { 'observatorys': observatorys} return render(request, 'observatorys/observatorys.html', context) Urls.py : urlpatterns = [ path('',views.observatorys,name="observatorys"), path(,'<int:observatory_id>', views.observatory, name="observatory"), Template.html : ... <img src="{{observatory.photo.url}}"> ... -
Does somebody know what technology is the best for the Seo of a blog website backend? [closed]
I heard that the webpage needs to be as light as possible. I am debating if to use php, ASP .Net core, laravel or django. The most comfortable for me would be ASP .Net so i just care about the SEO part. ....................... -
ajax object send to server
i wnat to send this data to that views.py var bookingData = { name: name, email: email, contact: contact, date: date, shift: shift, members: members }; // Send the booking data to the server using AJAX var xhr = new XMLHttpRequest(); xhr.open("POST", "/sendBookingData", true); xhr.setRequestHeader("Content-Type", "application/json"); // Set the event handler before sending the request xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { // Booking data successfully sent to the server // You can display a confirmation message or take other actions here alert("Booking successful!"); closePopup(); // Close the popup after successful booking } }; help me solve it out please. this project releated to the book guide system where the userinput details with the popup and when submitting the details it send to guide gmail from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def send_booking_data(request): if request.method == 'POST': # Extract data from POST request contact = request.POST.get('contact') date = request.POST.get('date') email = request.POST.get('email') members = request.POST.get('members') name = request.POST.get('name') shift = request.POST.get('shift') # Construct the email body with booking data email_body = f"New Booking Request\n\n" email_body += f"Name: {name}\n" email_body += f"Email: {email}\n" email_body += f"Contact: {contact}\n" email_body += f"Date: {date}\n" … -
AxiosError: Network Error when calling API from react native in django rest framework
I am running my app on my android device and i am not using any emulator. From postman I can call the APIs defined in django rest framework, however, when calling them from the front end, I am receiving the following error: AxiosError: Network Error Settings.py: DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cadence', 'rest_framework_simplejwt', 'rest_framework', 'corsheaders', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True SpitifyViews.py: class SpotifyViews(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def create_spotify_token(request): try: url = 'https://accounts.spotify.com/api/token' headers = { "content-type": "application/x-www-form-urlencoded" } data = { "grant_type": "client_credentials", "client_id": "220bc6fbfe2c4df28c4bad2b9095b391", "client_secret": "0bbb4cbabbdc4b229e9220c34c180758" } encoded_data = urlencode(data) response = requests.post(url, headers=headers, data=encoded_data) if response.status_code == 200: return JsonResponse(response.json()) else: return JsonResponse({"error": "Failed to get Spotify token"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except Exception as error: return JsonResponse({"error": str(error)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) JS Code: axios.defaults.baseURL = "http://localhost:8000/"; export const sendRequest = async (method, endpoint, body) => { const response = await axios.request({ method: method, url: endpoint, data: body, headers: { // Authorization: `Bearer ${localStorage.getItem("token")}`, }, }); if (response.status === 401) { // … -
how to fix django CSRF error for admin area?
I set up docker-compose to server django v5.0.6 and I see login page but after signin I face with CSRF error. my docker-compose containers: Nginx web (django container) postgres all the configs are correct and I can call APIs and see login page of admin area. nginx.conf server { listen 80; server_name example.com; location / { proxy_pass http://web:8000; } location /static { autoindex on; alias /static; } } .env ... DJANGO_ALLOWED_HOSTS=example.com,web CSRF_TRUSTED_ORIGINS=["example.com"] ALLOWED_HOSTS=['example.com'] ... how can I fix it? I try to setup based on the configs but I gave 403 error only for admin area. all APIs works fine. -
command `sudo systemctl start mybig_app` holds on and service stands in status loaded(activating) never turning to active
I have developed a quite big django app. I have deployed it at path /var/www/mybig_app/ on a server machine (raspberry pi) connected to my LAN. The app uses libraries stored in the virtual environment /var/www/mybig_app/venv/. I have configured a .wsgi file to instruct gunicorn to expose the app on port 8003 of localhost and nginx to stream content form port 8003 to port 3003. So, with current directory being /var/www/mybig_app/, I run python manage.py runserver localhost:8003 or /var/www/mybig_app/venv/bin/gunicorn mybig_app.wsgi:application --bind localhost:8003 and even if I have to wait about 5 seconds, in both cases I can reach my app from a browser of an external device connected to my LAN at address localhost:8003 (I have tryed to login as admin, access all the pages, it works, there is no error). Now I want to manage my app as a service via systemd. So I have prepared a .service file at /var/www/mybig_app/infrastructure/systemd/mybig_app.service, symbollically linked with ln -s /var/www/mybig_app/infrastructure/systemd/mybig_app.service /etc/systemd/system/ ln -s /var/www/mybig_app/infrastructure/systemd/mybig_app.service /etc/systemd/system/multi-user.target.wants/ loaded the configurations for systemd sudo systemctl daemon-reload sudo systemctl enable mybig_app.service (I have done this before for other apps, it works) In the end I want to start it, but when from directory /var/www/mybig_app I run sudo … -
How many lines of code does a website have with strong authentication and content management? [closed]
As someone who doesn't know much about technology, I wonder what's behind my everyday things? And how many lines of code do they have? I know this isn't specifically a problem, but I'm curious and would like to know, My apologies if it sounds a bit 'stupid' -
difficulty assigning a ForeignKey value field to a form within a loop
I'm encountering an issue with assigning a ForeignKey value to a form field within a loop. I have a Django application where users can submit answers to questions, and each answer can have multiple comments associated with it. To allow users to add comments to each answer, I've implemented a form within a loop. However, when users submit a comment using the form, instead of creating a CommentAForm object, it is creating a CommentQForm object. Despite attempting to pass the answer ID as a hidden field within the CommentAForm, the value doesn't seem to be correctly assigned to the CommentAForm. As a result, comments are not being associated with the correct form or model object, i don't know what is going on, How can I fix it views: def view_question(request, slug): question = get_object_or_404(Question, slug=slug) answers = Answer.objects.filter(post=question) answers_comment = CommentA.objects.filter(post__id__in=answers) # this is the comment form for each question if request.method == 'POST': comment_form = CommentQForm(request.POST) if comment_form.is_valid(): my_comment_form = comment_form.save(commit=False) my_comment_form.user = request.user my_comment_form.post = question my_comment_form.save() return redirect('View_Question', slug=slug) else: comment_form = CommentQForm() # This is the comment form each answer if request.method == 'POST': answer_comment_form = CommentAForm() if answer_comment_form.is_valid(): my_answer_comment_form = answer_comment_form.save(commit=False) my_answer_comment_form.user = request.user my_answer_comment.post … -
In mongodb(pymongo) how could i create only the missing path in a nested document
Im using django and mongoDB connected by Pymongo. And i made a collection of users that inside each user there are details, and a calender when the user first register the calendar is an empty array(could be changed if needed), in the calendar would be a list of years, inside every year a list of months, inside every month would be a list of days, and in every day a list of events. And i need that when a user wants to add an event to a specific date it would add it to the correct path meaning if the specified year allready exists it would insert the event in it and so on for the month and day. But if the year isnt exist yet it would create the needed path. Every thing i tried or not updating at all, or adding duplicates and ignores the allready created data. Does someone has a solution for that case? And if thats not the correct architecture for a mongo database feel free to improve it. Thank you very much. For example i tried users = db["users"] users.update_one({"_id": user}, {"$addToSet": {"year": year, "months": [{"month": month, "days": [{"day": day, "events": [new_event]}]}]}}}, upsert=True) But … -
the question is how to use LogoutView class in django to log out the user and also to redirect him to a specific url
misundersting of the usage of LogoutView based class. I would like to ask for an example in how to use this class to logout the user. I tried to use pass inside the class but it redirect me to an empty page -
How to run multiple websocket client connections?
Apologies in advance if this is a redundant question, I'm asking it here as the last resort, after having gone through a lot blogs & articles. Here's the situation: I have a django service(let's call it the "main" service) running an HTTP server & a WebSocket server using django-channels. I have a bunch of other django services(call them target services) wanting to connect to the websocket channels exposed by the main service And target each service needs to establish multiple websocket connections with the main service, and send/receive messages as long the connection is not closed by the main service. Here're some sample connection URLs: URL1 = "wss://main-service.com/ws-connection/1" URL2 = "wss://main-service.com/ws-connection/2" URL3 = "wss://main-service.com/ws-connection/3" And this list of URLs is obviously not known in advance, the main service sends us a mini payload which is used to generate the URL at runtime, and connection is established. The target service needs to have the ability to maintain thousands of websocket connection(serving as stateful connections) & it also needs to expose an HTTP API to serve direct requests. So far, I have gotten the target service API running as django project, and a basic websocket client, and the two look like this: … -
"... && coverage report" not working after switching to pytest-django
I was using unittest in Django to write tests and running the tests with this command: coverage run --omit='src/manage.py,src/config/*,*/.venv/*,*/*__init__.py,*/tests.py,*/admin.py' src/manage.py test src && coverage report It'd run the tests then display the .coverage generated by coverage run ... after running. After installing pytest-django and setting up pytest.ini, I've updated my command to: coverage run --omit='src/manage.py,src/config/*,*/.venv/*,*/*__init__.py,*/tests.py,*/admin.py' -m pytest && coverage report Note, I'm not using pytest-cov just yet. For some reason I can't figure out, the coverage report is not being displayed after the tests run. I can run each commands separately: The coverage run ... runs the tests and generates the report. The coverage report displays the report. I just can't get the report to display doing ... && coverage report after switching to pytest-django. Any reason for this? Versions: coverage = "^6.2" pytest-django = "^4.7.0" -
trouble in installation of django
I have been facing many issue regarding installation django on windows using pip. i have used "pip install django". But I am unable run the command "django-admin startproject myproject" it is showing following error: 'django-admin' is not recognized as an internal or external command, operable program or batch file. Please help me in installation of django on windows 11. please proide me with commans that to be run for installation in detail. -
How to test django channels between two physical devices over a wifi network
Can someone help me configure my django channel app in order for me to be able to test the chatting feature between two users. They must use two different devices and chat over a wifi network Looking through the net I can't find anything -
communication between the server and the user
Front end (React) and Back end (Django) are working on the local server and are sending information to the user, but the Front end code has been updated and the local server is working, but the users still see the old interface, what's the problem? please advise copied and pasted the new changes into the old code and added a new library, the program is working but the new changes are not visible with the old code -
Django login issue: Redirect to user panel not working despite status 200 in console [closed]
I'am building application in django and tailwind css to asking legal questions. I created user in django admin panel, created views etc. But after login(it is success 200 status), it doesn't work. I can't redirect user after login to user panel. How to do it, and where is error? https://github.com/marpot/lex_question Title: I'm encountering an issue with Django authentication where despite receiving a status 200 in the console upon logging in, I'm not redirected to the user panel as expected.I tried to change urls but it's incorrect I think. -
DjangoAdmin render BinaryField as image
I wrote middleware to catch requests and view them on admin page. It successfully views raw text request body, but fails on image render. admin.py class RequestLogEntryAdmin(admin.ModelAdmin): fieldsets = ( ('Request', { 'fields': ('request_headers', 'request_size', 'request_body_'), }) ) def request_body_(self, obj): if b'Content-Type: image/png' in base64.b64decode(obj.request_body): return obj.image_handler(bytes(obj.request_body)) return bytes(obj.request_body) models.py class RequestLogEntry(models.Model): # ... request_body = models.BinaryField(null=True) # ... def image_handler(self, binaryfield): return mark_safe(f'<img src="data:image/png;base64,{binaryfield}" width="150" height="150" />') Before saving request.body is being base64 encoded middleware.py # ... log_entry.request_body = base64.b64encode(request.body) # ... Current code produces the following: Base64 decoded request.body looks like this: My guess is that some extra data being mixed with the image bytes (like 'Content-Disposition' and 'Content-Type' headers), but I'm not sure how can I cut it out from the request body. -
AutocompleteFilter must inherit from 'FieldListFilter'
I want to write custom filter with drop down field using admin_searchable_dropdown I tried two ways too implement this and got error both times first way: the custom filter class PrimaryLabelFilter(AutocompleteFilter): field_name = 'primary_label' title = 'primary_label' in the admin using it like this list_filter = ( PrimaryLabelFilter, ) the error Forbidden (Permission denied): /admin/autocomplete/ model_admin = self.admin_site._registry[remote_model] ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^ KeyError: <class 'panel.backend.ad.models.label.Label'> HTTP GET /admin/autocomplete/?app_label=ad&model_name=ad&field_name=primary_label 403 [0.01, 127.0.0.1:52324] second way: in admin class list_filter = ( ('primary_label', PrimaryLabelFilter), ) the error <class 'panel.backend.ad.admin.ad.AdAdmin'>: (admin.E115) The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'. -
Git like view for dataframe comparison
I have two dataframe set called df1 and df2. I need to create a view in django template to compare these two dataframe in side by side. It should be looks like the git like comparison like below. I have tried the below but didn't work views.py # Convert DataFrames to lists of dictionaries for easier iteration df1_data = df1.to_dict(orient='records') df2_data = df2.to_dict(orient='records') # Combine the data to be passed to the template combined_data = list(zip(df1_data, df2_data)) return render(request, self.view_template,{ 'combined_data': combined_data } ) template {% block content %} <style> .row { display: flex; flex-direction: row; justify-content: space-between; } .column { flex: 1; } </style> <div class="container"> {% for row1, row2 in combined_data %} <div class="row"> <div class="column"> {% for key, value in row1.items %} <p>{{ key }}: {{ value }}</p> {% endfor %} </div> <div class="column"> {% for key, value in row2.items %} <p>{{ key }}: {{ value }}</p> {% endfor %} </div> </div> {% endfor %} </div> {% endblock %} -
weasyprint "Document has no attribute write_png"
I am writing a webapp in Python and Django. I use weasyprint to write pdf documents and I would like to use write_png() to get a png thumbnail of each pdf. This is from my views.py: pdf_letter = weasyprint.HTML(string=letter, base_url=static_url).render( stylesheets=[weasyprint.CSS(static_url + "/abrechnung/css/print-portrait.css")] ) pdf_table = weasyprint.HTML(string=table).render( stylesheets=[weasyprint.CSS(static_url + "/abrechnung/css/print-landscape.css")] ) val = [] for doc in pdf_letter, pdf_table: for p in doc.pages: val.append(p) pdf_file = pdf_letter.copy(val).write_pdf(f"{datetime.now()}.pdf") thumbnail = pdf_letter.copy(val).write_png(f"{datetime.now()}.png") When I try to run the program, I get the following error message in the browser: 'Document' object has no attribute 'write_png' pdf_file = pdf_letter.copy(val).write_pdf(f"{datetime.now()}.pdf") thumbnail = pdf_letter.copy(val).write_png(f"{datetime.now()}.png") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The weasyprint documentation on the write_png() function can be found here: https://doc.courtbouillon.org/weasyprint/v52.5/api.html#weasyprint.document.Document.write_png As I read the weasyprint documentation, I states that weasyprint.HTML.render() produces a weasyprint.document.Document. Said object has a function write_png(). Soooo.... WTF? What am I doing wrong here? I tried this for i, page in enumerate(document.pages): document.copy([page]).write_png('page_%s.png' % i) and this for page in document.pages: yield document.copy([page]).write_png() from the weasyprint tutorial (variables etc. adapted to my code of course) but none of both worked - I got the same error. Writing the pdf file alone is no problem, it is saved and returned later on. Problems just started when I … -
'svc_payment_dev'. The domain name provided is not valid according to RFC 1034/1035
Upon sending requests to the dockerized Django app through the API gateway layer using the container name (svc_payment_dev), I faced an issue indicating that the domain name provided is not valid acoarding to RFC 1034/1035 I know that underscores are typically not allowed in hostnames, and unfortunately, I'm unable to modify the container name at this time.So. I'm currently seeking a solution to modify the validation hostname in Django. Also, I've added the hostname to ALLOWED_HOSTS list but still encounter the "invalid hostname" error. ALLOWED_HOSTS = [ 'svc_payment_dev:8000' ] -
Nginx and SSL configuration inside docker container is not working
Am using following nginx conf file : server { listen 80; server_name domain; # Redirect HTTP to HTTPS return 301 https://$host$request_uri; } server { listen 443 ssl; server_name localhost; ssl_certificate /etc/nginx/cert/ddomain.crt; ssl_certificate_key /etc/nginx/cert/domain.key; location / { proxy_pass http://0.0.0.0:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } I am using the following docker file to run the container. This container runs 8000 port. FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set the working directory in the container WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y \ gcc \ gettext \ dbus \ libdbus-1-dev \ libcups2-dev \ libcairo2-dev \ libgirepository1.0-dev \ libgtk-3-dev \ libsecret-1-dev \ pkg-config \ wget \ nginx \ && rm -rf /var/lib/apt/lists/* # Copy the requirements file and install Python dependencies COPY requirements.txt /app/ RUN pip install --no-cache-dir -r requirements.txt # Copy SSL certificate files COPY ssl_certificates/domain.crt /etc/nginx/cert/domain.crt COPY ssl_certificates/domain.key /etc/nginx/cert/domain.key # Copy the Nginx configuration file COPY nginx.conf /etc/nginx/conf.d/default.conf # Copy the rest of the application files COPY . /app/ # Expose port 8000 to allow communication to/from server EXPOSE 8000 # Your application's command to run CMD ["python", "manage.py", "runserver", … -
Nginx gives 403 Forbidden error serving files
I am a newbie to nginx and run into a problem: nginx response with 403 Forbidden when I request example.com/media/ and all files inside the media folder. I am creating web application with python using Django Rest Framework. Here is my nginx file in /etc/nginx/sites-enabled/example.com: server { server_name example.com; access_log /var/log/nginx/example.com-access.log; error_log /var/log/nginx/example.com-error.log; location /media/ { alias /root/spaceai/backend/SpaceAI_Backend/apps/media/; } location / { client_max_body_size 0; gzip off; ## https://github.com/gitlabhq/gitlabhq/issues/694 ## Some requests take more than 30 seconds. proxy_read_timeout 300; proxy_connect_timeout 300; proxy_redirect off; proxy_http_version 1.1; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://localhost:8000; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name example.com; listen 80; return 404; # managed by Certbot Here is media folder rights: drwxr-xr-x 3 755 root 4096 May Head of /etc/nginx/nginx.conf: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # … -
DRF Forbidden (CSRF cookie not set.) from React axios POST request
As we know, we don't have access to Django CSRFToken in React by default, So we have to get it somehow. The solution was make a URL for receive CSRFToken in Response-Headers and set csrftoken cookie in browser. So I did it => Views.py @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response("CSRF cookie set.") CSRFToken.jsx import React, { useState, useEffect} from 'react'; import axios from 'axios'; export default function CSRFToken(){ useEffect(()=>{ const fetchData = async () => { try { const url = 'http://localhost:8000/csrf_cookie' const response = await axios.get(url,{ withCredentials: true, }).then(()=>{ console.log("CSRF Cookie set.") }) } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); }, []); return ( <> </> ) } Result => After that we can access to csrftoken and We can send it through X-CSRFToken Request-Headers. But the problem is when I send the request Django side won't accept that csrftoken and will reject that request. settings.py ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'App.apps.AppConfig' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ['http://localhost:5173'] Views.py @method_decorator(csrf_protect, name='dispatch') class …