Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django oAuth2 without saving the user into the database
I'm currently coding a website with Django and I successfully implemented an external oAuth2. (I'm not using any libraries) the problem is that the user is saved in the database. I would like to avoid it for hosting costs reasons. In my current project, the oAuth2 is purely for verification purposes. Is there a way in Django to log in a user in without saving him to the database? I would like the website to keep him logged in if the page is refreshed but logged out if the page is closed. Thanks! -
Using icontains for search queries with spaces in Django
I made simple search through my site, which is searching through several models within app. It worked fine until i realized that it can't search queries with spaces. Is there any option to search with spaces? Model: class Event(BaseModel): name = models.CharField(max_length=255, blank=True) description = models.TextField(blank=True) Object Event.objects.create( name="Test query event", description="Test Description" ) Query itself: query = "test query" Event.objects.all().annotate(search=SearchVector("name")).filter(search__icontains=query) I'm using latest versions of Django+DRF+django-filters, but it's possible to add other packages to project. -
Makemigration with django4.0.6 and python3.10.5 doesn't work
I'm currently coding a blog as a side project, whenever I make a considerable modification in my models, I cannot migrate. This is my model from ckeditor.fields import RichTextField from django.contrib.auth.models import User from django.db import models from django.template.defaultfilters import slugify from django.urls import reverse class Tag(models.Model): name = models.CharField(max_length=255, default="Uncategorized") class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('blog:home') class Post(models.Model): ACTIVE = 'active' DRAFT = 'draft' CHOICE_STATUS = ( (ACTIVE, 'Active'), (DRAFT, 'Draft') ) title = models.CharField(max_length=255) title_color = models.CharField(max_length=50, default="white") header_image = models.ImageField(upload_to='images/headers', null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) table_content = RichTextField(default="CONTENTS", blank=True, null=True) body = RichTextField(blank=True, null=True) snippet = models.CharField(max_length=255, default="") date_published = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=CHOICE_STATUS, default=DRAFT) slug = models.SlugField() tag = models.ManyToManyField(Tag) def __str__(self): return self.title + ' | ' + self.author.get_full_name() def get_absolute_url(self): return reverse('blog:article_details', args=(str(self.id), self.slug)) @property def date(self): return self.date_published.date() def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) class PostPicture(models.Model): name = models.CharField(max_length=255, default="") files = models.FileField(upload_to="images/post") def __str__(self): return self.name Now, in my model, I had the class named Category and decided I don't need it anymore and just renamed it Tag. When I make migrations, I have this error … -
Dajngo template rendering
When i render blogpost.html page i can't see any content in my page. Please any devloper help me. My code look like this. My urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='Blog_home'), path('<slug:slug>', views.blogpost, name='blogpost'), ] my views.py from django.shortcuts import render from django.http import HttpResponse from blog.models import Post # Create your views here. def index(request): post = Post.objects.all() context = {'post':post} return render(request, 'blog/bloghome.html', context) def blogpost(request, post_id): post = Post.objects.filter(slug=slug) context = {'post':post} return render(request, 'blog/blogpost.html', context) Template Name:- blogpost.html {% extends 'basic.html' %} {% block title %}Blog{% endblock title %} {% block body %} <div class="contaier"> <div class="row"> <div class="col-md-8 py-4"> <h2 class=" blog-post-title">{{post.title}}</h2> </div> </div> </div> {% endblock body %} -
Where can I find a list of all available methods of a request object in Django DTL?
How can I know what methods are used for request object in DTL? {{ request.WHAT }} -
Django CMS: Error while setting up django-cms
I'm having a WSGI error while following the installation set up for django-cms from th official documentation. I ran test with python manage.py cms check and it was sucessful. Checking django CMS installation Sekizai Sekizai is installed [OK] Sekizai template context processor is installed [OK] Sekizai namespaces 'js' and 'css' found in 'home.html' [OK] Plugin instances ================ Plugin instances of 0 types found in the database [OK] The plugins in your database are in good order [OK] Presence of "copy_relations" All plugins and page/title extensions have "copy_relations" method if needed. [OK] PlaceholderField PlaceholderField configuration okay [OK] OVERALL RESULTS 9 checks successful! Installation okay But when I try running server, I get this thread of errors. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 22, 2022 - 08:47:41 Django version 3.2.14, using settings 'projcms.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\adedi\Documents\Dev\Projects\Django\dj-cms\env\lib\site-packages\django\utils\module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\adedi\Documents\Dev\Projects\Django\dj-cms\env\lib\site-packages\django\core\servers\basehttp.py", … -
Celery unavailable after dockerization in a Django app
I have a Django app that I've been trying to dockerize. I've successfully dockerized Django with gunicorn and nginx so the main part of the app is running. However, I also have tasks that need to be run using Celery. I dockerized rabbitmq, and I think that was successful, as before installing it I had Connexion refused and I don't anymore. I only lack Celery to be dockerized so, as my tasks are not executed nor stored in the database, my Celery configuration is probably wrong, however I couldn't find where I'm going wrong with it. Here is my docker-compose.yml: version: '3.8' services: django_gunicorn: volumes: - static:/app/static - media:/media env_file: - env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static - media:/media ports: - "80:80" depends_on: - django_gunicorn rabbitmq3: image: rabbitmq:3-alpine ports: - 5672:5672 celery: restart: always build: context: . command: celery -A main worker -l info env_file: - env depends_on: - rabbitmq3 - django_gunicorn volumes: static: media: Dockerfile: FROM python:3.10.5-alpine RUN pip install --upgrade pip RUN wget https://upload.wikimedia.org/wikipedia/commons/b/b9/First-google-logo.gif -O media/media.gif COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./src /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] entrypoint.sh: #!/bin/sh python manage.py migrate python … -
Django placing order (like restaurant etc)
I'm building an online restaurant website, I have an app with a few models containing the Menu. I want to add another app that utilizes the Menu models to populate multiple choice field. Something like an ordering page. But I've no idea how to do that. Also, how should my order model look like? -
I am trying to create an app that uses the Django REST Framework and Flask, but it is not working correctly
I'm having trouble with my python app using django and flask framework. It's creating a database and all of that stuff but when it tries to make a request to /api/v1/users, it always comes back with data errors. I've tried looking at the logs for the site and it says the same thing "connection refused" when the server makes a connection attempt, and I can't seem to figure out why this is happening. My code looks like this right now: from flask import Flask, jsonify, request import datetime app = Flask(__name__) db=sqlite3.connect('data.db') class User(object): def __init__(self, id, name, email, password): self.id = id self.name = name self.email = email self.password = md5_hash(password).hexdigest() def __repr__(self): return "<User %s>" % (self.id,) @app.route("/api/v1/users", methods=('GET', 'POST')) def users(): if request.method == 'GET': users = db.execute('SELECT * FROM user ORDER BY id ASC').fetchall() data = dict(users=users) return jsonify(data) elif request.method == 'POST': newuser = User(request.form.get('id'), request.form.get('name'), request.form.get('email'), request.form.get('password')) db.executemany("INSERT INTO user VALUES (?,?,?,?)", (newuser.id, newuser.name, newuser.email, newuser.password)) return jsonify(status="ok") else: return "Invalid method." @app.errorhandler(404) def page_not_found(e): return jsonify(status='Not Found') if __name__ == "__main__": app.run(host='0.0.0.0', port=5000) The error message I get in the logs is: 127.0.0.1 - - Referer: http://localhost:5000/api/v1/users 127.0.0.1 - - Connection: close 127.0.0.1 … -
Django User cannot login
I made a simple register and login script, the register script works and sends the user information to a database but the login does not log the user in. This is the login function in views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from .forms import LoguserForm # Create your views here. def loginpage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') context = {} return render(request, 'accounts/login.html', context) This is the login.html file: <body class="container"> <div class="loginbox"> <form id="login" class="input-group"> {% load static %} <img src="{% static 'accounts/images/logo.png' %}" id="loginlogo"> {% csrf_token %} <input type="text" class="inputfield" name="username" placeholder="Username"> <input type="password" class="inputfield" name="password" placeholder="Password"> <input type="submit" class="submitbtn" value="Login"></input> {% for message in messages %} <p>{{message}}</p> {% endfor %} <p1 class="registerp">New here? <a href="/register">Register</a></p1> </form> </div> This is the homepage code: def home(request): return HttpResponse('Home Page') When I try to login instead of redirecting me to the home page the URL changes to: http://127.0.0.1:8000/?csrfmiddlewaretoken=F63yG1ZNQTr4e6tRvjvj5TraSLeDDxAGCm1S89k4yuq21DyPgS4AlnfxA2KtnrA4&username=Tester&password=888tyuuyt -
how to display only domain name of the link in django?
i have a link <a href="{{ article.url }}" target="_blank">{{ article.title | safe}}</a> and link url name {{ article.url }} in my html file but i want to display only domain.com name without full url. i tried from urllib.parse import urlparse url = models.URLField() domain = urlparse(url).netloc in models.py than {{ article.domain }} in html file but get AttributeError: 'URLField' object has no attribute 'decode' -
Update form store none value when I submit the update form. How can I fix It?
I made a feedback form (def feedBack) so that a user can give feedback. It's working well. Now my motive to create an update form so that a user can be able update their feedback. I also have written a view for update feedback (def UpdateFeedback). But it's not working perfectly. When I submit the update form, then it updates none. Where did the actual problem occur? views.py: This view for storing feedback and it's working well. def feedBack(request,quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) if request.method == "POST" and request.user.is_authenticated: try: ProductREVIEWS.objects.create( user=request.user, product=quick_view, feedBACK=request.POST.get('feedBACK') ) return redirect('quick_view', quick_view_id) except: return redirect('quick_view', quick_view_id) else: return redirect('quick_view', quick_view_id) this view for update the feedback, but it's store none def UpdateFeedback(request, id): feedback = ProductREVIEWS.objects.get(pk=id) product_id = feedback.product.id reviewers = feedback.user if request.method == "POST": form = UpdateFeedbackForm(request.POST) if form.is_valid() and reviewers.id == request.user.id: UpdateFeedbackForm(request.POST) feedBACK = form.cleaned_data.get('UpdateFeedBACK') feedback.feedBACK = feedBACK feedback.save() messages.success(request, "Feedback is updated") return redirect('quick_view', product_id) forms.py: class UpdateFeedbackForm(forms.ModelForm): class Meta: model = ProductREVIEWS fields = ('feedBACK') labels = { 'feedBACK':'Change Your View' } widgets = { 'feedBACK':forms.Textarea(attrs={'class':'form-control', 'style':'font-size:13px;'}) } models.py: class ProductREVIEWS(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userREVIEW',on_delete=models.CASCADE) product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE) feedBACK = models.TextField(blank=True, null=True) urls.py: path("feedBack/<int:quick_view_id>/", views.feedBack, name="feedBack"), path("UpdateFeedback/<int:id>/", … -
APScheduler is not starting on runserver in django
I followed a particular tutorial to implement APScheduler in my application but when I run my project the job is not called at all and I am having a hard time figuring what I did wrong The project directory looks like the following: reports auto_mails __init__.py send_mail.py migrations __init__.py admin.py allotmentkeys.py apps.py models.py tests.py urls.py views.py and views.py class AutoMails(APIView): def send_mail_test(self): subject = 'Password Reset Request' message = ' Password Reset Request. OTP is 454545 ' email_from = 'xxxx@xxx.com' recipient_list = ['yyy@xxx.com', ] print("called") send_mail(subject, message, email_from, recipient_list, fail_silently=False) send_mail.py from apscheduler.schedulers.background import BackgroundScheduler from reports.views import AutoMails def start(): print("reached") scheduler = BackgroundScheduler() mail = AutoMails() scheduler.add_job(mail.send_mail_test(),"interval", seconds=10, id="test_mails_001", replace_existing=True ) scheduler.start() apps.py from django.apps import AppConfig class ReportsConfig(AppConfig): name = 'reports' def ready(self): print("Sending Mails ..") from auto_mails import send_mail send_mail.start() urls.py path('auto-mails/', AutoMails.as_view()), When I run the project using python manage.py runserevr I get the following: C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\reports\views.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 22, 2022 - 12:25:31 Django version 3.0.5, using settings 'multitennant_v2.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. where I was expecting to see Sending Mails.. given … -
How to enable URL MASKING changing HTTP HEADERS
I have a django application (version 4.0.3) and I want to URL MASK some specific URLs using new purchased domains (in this case GoDaddy) So what I want to do is: www.originaldomain.com/url1 beeing masked with www.newdomain.com. But when I redirect with mask in domain www.newdomain.com some HEAERS do not allow it (I know because GoDaddy tech support said me "something is blocking it"). If I do a normal redirect (301 or 302) it works, but not with URL Masking. I tryied removing X-Frame-Option: Deny using a django decorator to the view but still not able to make it work. Current response headers HTTP/1.1 200 OK Date: Fri, 22 Jul 2022 06:47:40 GMT Content-Type: text/html; charset=utf-8 Transfer-Encoding: chunked Connection: keep-alive Vary: Accept-Encoding Vary: Cookie, Accept-Language Content-Language: es X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Set-Cookie: csrftoken=UJp7VSdbT7BnFmc9wKnFZeKSKWjtGbLcEaLEqrZ0MAj8NhU69MDjZQIgWj5LhnWw; expires=Fri, 21 Jul 2023 06:47:40 GMT; Max-Age=31449600; Path=/; SameSite=Lax Set-Cookie: sessionid=bjtb3e42z9h9wd5tixsw3xpj23kiao1u; expires=Fri, 05 Aug 2022 06:47:40 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax X-Clacks-Overhead: GNU Terry Pratchett Content-Encoding: gzip Server: PythonAnywhere An explanation of how to find what is blocking it would also be very appreciated (like using -
How to change max_length of username in AbstractUser
Model.py class User(AbstractUser): username = models.CharField(max_length=20) Why does the phrase below appear in cmd? WARNINGS: ourtube.User: (auth.W004) 'User.username' is named as the 'USERNAME_FIELD', but it is not unique. HINT: Ensure that your authentication backend(s) can handle non-unique usernames. -
Setting value to default in a django for loop
I've been stuck on a rather simple issue, where i'm trying to either set a value on a variable in a for loop, or setting the default data to N/a. I set up a datatable that gathers lots of data, but i need to return 2 of the variables to N/a if not found in the for loop. In the code example below, you can see a generic example of what i've tried. In the 2 for loops i'm trying to set a global var, that i can than access outside of the for loop. I've done some reading and i just can't figure out the smartest way of doing this. Hence me asking the question here. Please do ask if you need additional information. {% for vlan, macs in info.vlans.items %} {% for mac in macs %} {% endfor %} {% endfor%} {% if vlan %} <td>{{vlan}}</td> {% else %} <td>N/a</td> {% endif %} {% if mac %} <td>{{mac}}</td> {% else %} <td>N/a</td> {% endif %} I did also try to set the values within the for loop, but it won't work for the ones that do not have a mac or vlan assigned, as it does not set … -
Why DjangoObjectPermissions is not working for admin user?
Problem: I have assigned DjangoObjectPermissions which is working perfectly working for normal users but Its not workign for admin users. models.py class Transformer(models.Model): name = models.CharField(max_length=150, unique=True) alternate_mode = models.CharField( max_length=250, blank=True, null=True) description = models.CharField( max_length=500, blank=True, null=True) alive = models.BooleanField(default=False) class Meta: ordering = ('name',) def __str__(self): return self.name serializers.py class TransformerSerializer(serializers.ModelSerializer): class Meta: model = Transformer fields = "__all__" views.py class TransformerList(generics.ListCreateAPIView): queryset = Transformer.objects.all() serializer_class = TransformerSerializer permission_classes = [DjangoObjectPermissions, ] def perform_create(self, serializer): instance = serializer.save() assign_perm("delete_transformer", self.request.user, instance) class TransformerDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Transformer.objects.all() serializer_class = TransformerSerializer permission_classes = [DjangoObjectPermissions, ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'snippets', 'class_based_api_views', 'guardian' ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'guardian.backends.ObjectPermissionBackend', ) Testing created admin user -> username=admin created normal user -> username=user3 created one transformer post using user3 user. Object detail view Image of Object detail view Object's permission Image of object's permission user3 can delete his own post as expected Image for user3 can delete his own post as expected Admin can do everything on object: not expected Admin can do everything on object: not expected Question: Why Admin user can edit/delete object which he dont have permission. -
Resume parser in django
I need to build a resume parser web application in django where candidates just uploads their resume and the personal information fields in the form gets automatically filled. Candidates can upload resume in any format like doc,docs,jpg etc. Can anyone help me in how do I go about doing it, which libraries is good for this job I am running short on time, would appreciate the little help I get. Thank you -
Django CSRF token issue in incognito mode for all browsers
I have a django version 3.1.5 where i can login to admin using incognito mode of browser by entering username and password. But when I upgrade my django version to 3.2.14 and try to login admin using incognito mode of browser it shows Forbidden (CSRF cookie not set.). Is there is any method to solve this issue. -
Could not render the home page template in DJango mini project,
views.py: from django.shortcuts import render from django.shortcuts import HttpResponseRedirect from myapp.form import LoginForm from myapp.models import Login # Create your views here. def index(request): myForm=LoginForm() if request.method=="POST": name=request.POST['name'] password=request.POST['password'] new_data=Login(Name=name,Password=password) new_data.save() form=LoginForm(request.POST) if form.is_valid(): return HttpResponseRedirect("thanks") return render(request,'index.html',{'form':myForm}) def thankyou(request): return render(request,'thanks.html') and this is my urls.py: from django.contrib import admin from django.urls import path from myapp import views urlpatterns = [ path('',views.index), path('thanks',views.thankyou), path('admin/', admin.site.urls), ] i have created a model template view for sample login form, except home page, everything is fine, even superuser also created. form.py: from dataclasses import field from pyexpat import model from django import forms from myapp.models import Login class LoginForm(forms.Form): class Data: model=Login, field=[ 'Name','Password' ] admin.py: from django.contrib import admin # Register your models here. from myapp.models import Login admin.site.register(Login) models.py: from django.db import models # Create your models here. class Login(models.Model): Name=models.CharField(max_length=20) password=models.CharField(max_length=20) base.html: <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% block content %} {% endblock content %} </body> </html> index.html: {% extends 'base.html' %} {% block content %} <h1>Application Form</h1> <form action="" method="post"> Name: <input type="text" name="name"><br> Password:<input type="password" name="password"><br> <input type="submit"> </fomr> {% endblock content %} thanks.html: {% extends 'base.html' %} {% block content %} <h1>Thankyou</h1> {% endblock … -
Django-single user with multiple employee account for each organization flow
Im creating an application where user is having multiple employee account with each organization. When i login with user credential it has redirect to choose organization page and after choosing organization i has to redirect to dashboard page where all details related to the organization should be displayed. My doubt is when im doing multiple api calls in dashboard page whether i need to pass organization id in all requests? ex: organization//team//members/ if this goes like this means url will grow long.Please help on this. Thanks in Advance. -
local variable 'zip' referenced before assignment in django
when i am running this code in django its throwing error UnboundLocalError: local variable 'zip' referenced before assignment. what to do i dont know can anyone please help me out. import matplotlib.pyplot as plt plt.figure(figsize=(10,8)) # Black removed and is used for noise instead. unique_labels = set(labels) colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))] for k, col in zip(unique_labels,colors): if k == -1: # Black used for noise. col = [0, 0, 0, 1] class_member_mask = labels == k xy = embedding[class_member_mask & core_samples_mask] plt.plot( xy[:, 0], xy[:, 1], "o", markerfacecolor=tuple(col), markeredgecolor="k", markersize=14, ) xy = embedding[class_member_mask & ~core_samples_mask] plt.plot( xy[:, 0], xy[:, 1], "o", markerfacecolor=tuple(col), markeredgecolor="k", markersize=6, ) plt.title("Estimated number of clusters: %d" % n_clusters_) -
What is the use of .changed() in django celery. : PeriodicTasks.objects.changed(self)?
This code has been written by someone else and i just don't know what does .changed do? class PeriodicAlarm(PeriodicTask): title = models.CharField( ) user = models.ForeignKey( ) severity = models.IntegerField() notify = models.BooleanField( ) emails = ArrayField() category = models.IntegerField() periodicity = models.CharField() def save(self, *args, **kwargs): if self.id is None: create = True else: create = False if create and self.user.get_account().has_alarm_limit_reached(): raise ValidationError({'non_field_error': 'Alarm limit reached'}) self.name = uuid.uuid4().hex # self.name = self.user.email + '|' + self.title super(PeriodicAlarm, self).save(*args, **kwargs) if create: self.args = json.dumps([ str(self.id), str(self.analytics.id), str(self.user.id), ]) self.task = 'sample_path.tasks.execute_event_query' super(PeriodicAlarm, self).save(*args, **kwargs) PeriodicTasks.changed(self) What does .changed() do??? -
Django filter charfield by greater than X principle
Possible duplicate, but no answers so far got any close to the solution. Imagine you have a charfield like this: 1.1.1.1 arriving in the request. I.e. basic semantic version. You need to filter all the objects in the queryset, where their version charfield is greater than this. For example we have such records in the DB: 0.0.0.0 0.0.0.1 1.0.0.0 1.1.1.1 1.1.1.2 2.2.2.2 And in the example provided I gave the version number as 1.1.1.1. So filtering by "greater than this" principle we will get only [1.1.1.2, 2.2.2.2]. Right now I'm filtering just by using regex. But how to do this using django ORM? -
Simulate CSRF attack in Django Rest Framework
I'm trying to get an understanding of how CSRF tokens work, currently my goal is to create a situation where the CSRF attack is possible. I'm hosting two Django apps locally on different ports. I access one by localhost:8000, the other by 127.0.0.1:5000 -- that ensures cookies are not shared between apps. There's an API view class ModifyDB(APIView): def post(self,request,format=None): if request.user.is_authenticated: return Response({'db modified'}) else: return Response({'you need to be authenticated'}) which shouldn't be accessed by unauthenticated users. The "malicious" site has a button that's supposed to trigger the attack when a user is logged on the target site: const Modify = () => { const onClick = async e => { e.preventDefault(); const instance = axios.create({ withCredentials: true, baseURL: 'http://localhost:8000', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }) const res = await instance.post('/api/modifydb'); return res.data } return ( <button class = 'btn' onClick = {onClick}> send request </button> ) } My authentication settings are as follows: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'my_proj.settings.CsrfExemptSessionAuthentication', ], } where CsrfExemptSessionAuthentication is a custom class that disables csrf protection for my educational purposes: class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return django.middleware.csrf.CsrfViewMiddleware is also disabled. Both CORS_ALLOW_ALL_ORIGINS and CORS_ALLOW_CREDENTIALS are set to true. My question …