Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-admin - How to add a section between form fields and auto-fill
I want to add an extra section (a <div>) on a django-admin form, which gets filled automatically with related data as I select a ForeignKey on a form field. For example, suppose there's a model Student, that is used in another model Classroom. class Classroom(models.Model): student_name = models.ForeignKey(Student, on_delete=models.DO_NOTHING) I want the Classroom admin form page to look like the following image: As I select a student named "John", the related details should automatically show up. -
JSON Schema Syntax Checker
I need to make a JSON schema to json validator web app using Django. I've already made the UI with login features and somewhere to upload files and now I'm working on the main logic. I'm going through different ideas on how to implement it and I wondering if there was a way I could implement jsonschema into my project. This is just an idea and I'm not sure if I should do that or just make a validator from scratch. -
LOGIN command error: BAD [b'Not enough arguments provided ]
I tried to make a login page from scratch using imaplib and the Django framework using two forms inputs, one for email and another for password, but it has been showing the login command error on the Django error page. This is the view from my app: from django.shortcuts import render from .forms import AccountEmail, AccountPassword from django.http import HttpResponse import imaplib username = '' password = '' def get_email(request): template = 'email_account/index.html' if request.method == 'POST': email_input = AccountEmail(request.POST) password_input = AccountPassword(request.POST) if email_input.is_valid(): username = email_input.cleaned_data['email'] if password_input.is_valid(): password = password_input.cleaned_data['password'] else: email_input = AccountEmail() password_input = AccountPassword() return render(request,template,{'email': email_input, 'password': password_input}) def inbox(request): server = imaplib.IMAP4_SSL('imap.gmail.com') server.login(username, password) server.select('inbox') ch, data = server.search(None, 'all') mail_id = data[0] lst = mail_id.split() return render("<h2>lst</h2>") And my this is my code from the forms.py file: from django import forms class AccountEmail(forms.Form): email = forms.EmailField(max_length=50, widget=forms.TextInput(attrs={'placeholder': 'Introduce your email'})) class AccountPassword(forms.Form): password = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Introduce your password'})) -
script is not running on ajax loaded content in django
I have a web page in which i have some nested div elements forming one complete set which can be loaded dynamically when user clicks load more button. the web page has some script which change the style of the above mentioned div element, when the page first loaded. when the user clicks load more button, ajax call is made and the html received is appended after the above mentioned 'div'element. the problem is that only raw html is appended to the page, without running the script on it, the result is that only the div which is present when the page is first loaded is getting style by the script. how to get script to run on the dynamically loaded element too? django views: from django.shortcuts import render from printools.models import Images from django.template import loader from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): image_set = Images.objects.all()[:3] template = loader.get_template('printools/index.html') context = { 'images':image_set, } return HttpResponse(template.render(context,request)) def ajaxImages(request): total_image = Images.objects.all().count() n = int(request.POST['nImages']) template = loader.get_template('printools/ajaxImages.html') data = Images.objects.all()[n:n + 3] context = { 'images': data, 'n_images':total_image, } return HttpResponse(template.render(context, request)) ajax call: $('#js-single-more').on('click',function (event) { console.log('clicked'); $.ajax({ type: 'POST', β¦ -
Incorrect longitude/latitude saved to PointField via admin widget
I have a basic GeoDjango PointField: point = models.PointField(srid=4326, null=True) When using the admin, I would expect this to be saved in the database as (for example, London): SRID=4326;POINT (-94.577597, 39.057294) but instead, if I place the marker on London, I get: SRID=4326;POINT (-19067.91721243037 6711435.410105047) Where the longitude/latitude are way off. I've tried manually setting the Point to the location: obj.point = Point(-94.577597, 39.057294) obj.save() but the widget is then rendered way off. So it seems that the wrong latitude and longitude are being saved to the field. I've tried to manually override the widget to make sure the correct SRID is being used on the widget with: class Meta: model = models.MyModel fields = "all" widgets = { 'point': widgets.OSMWidget(attrs={ 'map_srid': 4326, 'map_width': 800, 'map_height': 500 }) } But no luck. I have all the dependencies for GeoDjango installed, I've enabled the postgis extension on my database and I the correct engine in use: DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis' I also have added django.contrib.gis to INSTALLED_APPS. I'm using the default form widget, but I'm wondering might the widget be the problem? -
How to show error messages in a custom signup template in Django
I'm trying to show error message in my custom signup template. Just to verify my below codes work, I used the {{ form.as_table }} and it shows error message properly. However, when I use my custom signup template, it doesn't show any error message when I cause an error on purpose on the signup form. HTML <form class="form-signin" method="POST"> {% csrf_token %} <div class="container"> <div class="jumbotron"> <a class="navbar-brand js-scroll-trigger" href="{% url 'boutique:index' %}"><img width="165" height="30" src="{% static 'boutique/img/modvisor_logo_black.png' %}"></a> <br><br> <div class="text-center mb-4"> <h1 class="h3 mb-3 font-weight-normal">Join Modvisor</h1> <p class="error-message"> {% if form.non_field_errors %} {% for error in form.non_field_errors %} {{ error }} {% endfor %} {% endif %} </p> </div> <div class="form-label-group"> <input type="text" id="inputEmail" class="form-control" name="username" placeholder="Email address" required autofocus> <label for="inputEmail">Email</label> </div> <div class="form-label-group"> <input type="password" id="inputPassword1" class="form-control" name="password1" placeholder="Password" required> <label for="inputPassword">Password</label> </div> <div class="form-label-group"> <input type="password" id="inputPassword2" class="form-control" name="password2" placeholder="Password" required> <label for="inputPassword">Confirm Password</label> </div> <!-- <div class="form-label-group"> <input type="password" id="inputPassword" class="form-control" name="password2" placeholder="Password" required> <label for="inputPassword">Confirm Password</label> </div> <div class="checkbox mb-3"> <label> <input type="checkbox" value="remember-me"> Remember me </label> </div> --> <button class="btn btn-success btn-block" type="submit">Sign Up</button> <br> <a href="{% url 'login' %}"><button class="btn btn-secondary btn-block" type="button">Back</button></a> <p class="mt-5 mb-3 text-muted text-center">&copy; 2018 Modvisor All β¦ -
Django testing: how to add app to `Synchronizing apps without migrations` section
When I run the tests with a verbosity level of 3 (-v 3), I see that my apps are NOT categorized under Synchronizing apps without migrations... I would ask how to add my apps to this section. I have them in INSTALED_APPS list. after running tests I have: django.db.utils.OperationalError: no such table notice. Why is that? How to add those apps to Synchronizing apps without migrations... Migrations are in another app. Both apps have connected data base. When I run my code, everything is OK. Test, on the other hand, fail. -
feed page - django/HTML
I am creating a social network website using Django, HTML. I have a blog list page which lists all the posts from users. How can I list the posts in separate tiles or containers on the blog list page like fb. Currently it displays all the posts in a single container. But I want them to separate. Thanks. blog_list.html <section> <br> <div class="container" id ="main-cont"> <div class="row"> <div class="panel panel-default post"> <div class ="panel-body"> <div class ="row"> <div class = "col-sm-1"> <a class ="post-avatar thumbnail" href = "#"><img src ="{% static 'img/group.png' %}"></a> <!-- <hr>Created By: {{ post.author }}--> <div> {% for post in post_list %} <div class="post"> <h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}<br></h2> {{ post.description |truncatechars:170 }}</a> <br> <br> <p><img src = "{% static 'img/thumbsup.png'%}"> <a class = 'like-btn' data-href='{post.get_api_like_url}' data-likes = '{{ post.likes.count }}' href ='{{ post.get_like_url }}'>{{ post.likes.count }} Like</a></p> </div> <form method = "post"> {% csrf_token %} {{form}} </form> <a href="{% url 'post_detail' pk=post.pk %}"></a> </div> {% endfor %} </div> {% endblock %} -
Django storages S3 - File loading
I have django 1.11 with latest django-storages, setup with S3 backend. I am trying to programatically instantiate an ImageFile, using the AWS image link as a starting point. I cannot figure out how to do this looking at the source / documentation. I assume I need to create a file, and give it the path derived from the url without the domain, but I can't find exactly how. The final aim of this is to programatically create wagtail Image objects, that point to S3 images (So pass the new ImageFile to the Imagefield of the image). I own the S3 bucket the images are stored in it. Uploading images works correctly, so the system is setup correctly. -
django prevent accessing variable before it's defined on submit
I have the following django view that works great except in the instance of clicking the submitted button on the previous view i'm sending the POST information from. def submitted(request): # sets the employeentname to the username from the POST of results owner = ADMirror.objects.get (employeentname=request.POST.get('userpost')) # sets the firstname of owner firstname = owner.employeefirstname # sets the lastname of owner lastname = owner.employeelastname # gets the POST list for the report_id values in the checkboxes for application names checkedlist = request.POST.getlist('report_id') reportdetail = QvReportList.objects.filter(report_id__in = checkedlist).values_list('report_name_sc', flat = True).distinct() # gets the timestamp from the system clock when the submit button is pressed access_request_date = timezone.now() #### Unused at this time, but we can pull the division CFO and facility CFO based on the tables Gregg created in the SQL server database. We'll let the workflow tool handle this part. # facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = '34222', active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True) # divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = '34222', active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True) #print (facilitycfo) #print (divisioncfo) # gets the access level ie facility, division, market, group, corporate from the results.html POST request sent to submitted.html selectedaccesslevel = request.POST.get('accesslevelid') # sets access β¦ -
Django: remove duplicates (group by) from queryset by related model field
I have a Queryset with a couple of records, and I wan't to remove duplicates using the related model field. For example: class User(models.Model): group = models.ForeignKey('Group') ... class Address(models.Model): ... models.ForeignKey('User') addresses = Address.objects.filter(group__id=1).order_by('-id') This returns a QuerySet of Address records, and I want to group by the User ID. I can't use .annotate because I need all fields from Address, and the relationship between Address and User I can't use .distinct() because it doesn't work, since all addresses are distinct, and I want distinct user addresses. I could: unique_users_ids = [] unique_addresses = [] for address in addresses: if address.user.id not in unique_users_ids: unique_addresses.append(address) unique_users_ids.append(address.user.id) print unique_addresses # TA-DA! But it seems too much for a simple thing like a group by (damn you Django). Is there a easy way to achieve this? -
Django : fixtures object not retrievable
Strange thing is happening. Here is a part of my fixture : { "model": "mezzanine_agenda.event", "pk": 1, "fields": { "comments_count": 0, "keywords_string": "", "rating_count": 0, "rating_sum": 0, "rating_average": 0.0, "site": 1, "title": "event search", "slug": "event-search", "_meta_title": "", "description": "event search", "gen_description": true, "created": "2018-05-25T15:49:55.223Z", "updated": "2018-05-25T15:49:55.257Z" } And here is my test : class FrontTest(LiveServerTestCase): fixtures = ['event.json'] @classmethod def setUpClass(cls): super().setUpClass() print(Event.objects.all()) And the output : [] Do someone know why my fixture is not loaded ? -
Django/postgres transaction isolation level setting ignored
I have an issue setting transaction isolation level. I want the most strict serializable, while the default is read committed. I am using: Django==1.10.6 psycopg2==2.5.1 Running on heroku. Based on the documentation: https://docs.djangoproject.com/en/1.10/ref/databases/#isolation-level I have the following settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'OPTIONS': { 'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE, } } if on_heroku: DATABASES['default'] = dj_database_url.config() Here's the view code: @require_http_methods(["POST"]) @transaction.atomic @login_required() def api_test_add_one(request): cursor = connection.cursor() cursor.execute('SHOW default_transaction_isolation') logger.info("aa: " + str(cursor.fetchone())) return HttpResponse("{}", content_type="application/json") The output is: aa: (u'read committed',) I have run different tests simultaneously accessing the same endpoint, incrementing an integer in DB and confirmed that transactions were not isolated. -
Django delete() method has no effect
I've been working with Django for about a year, and I've recently started a Django 2 application projet. My problem is that when I use delete() on a model instance, the object isn't removed from the database. Below is related models.py code class Project (models.Model): owner = models.ForeignKey (User, ...) participants = models.ManyToManyField (User, ...) class ProjectFile (models.Model): uploader = models.ForeignKey (User, blank=True, on_delete=models.CASCADE) project = models.ForeignKey (Project, related_name="documents", blank=True, on_delete=models.CASCADE) file = models.FileField (verbose_name=_("Fichier"), upload_to=upload_to_projects) And below is the related view @require_ajax def remove_file(request, project_id, file_id): file = get_object_or_404(ProjectFile, id=file_id, project=project_id) file.delete() return HttpResponse(status=200) Whether I try to delete from this view or from shell with ProjectFile.objects.get(id=1).delete() everything seems fine (it returns (1, {'Ideaters.ProjectFile': 1})) but the object isn't deleted from the database. I've also noticed that when I try to delete a project, I get this error: ForeignKey constraint violation Ideaters_projectfile_project_id_c6254cf6_fk_Ideaters_project_id DETAIL: The key (project_id)=(1) isn't present in the table Ideaters_project But I don't understand it, as Project table has no relation to itself. Anyway, I guess may be related to my foreign keys definition but though I went through 2.0 Documentation, I can't see my mistake. -
Database slow with Django and PostgreSQL
I recently ran some standard package updates on my Ubuntu server, and now my Django site with a Apache ModWSGI+PostgreSQL backend is running extremely slowly. Pages that used to load in 2 seconds are now taking 30 seconds. Checking the running queries with SELECT * from pg_stat_activity, I'm seeing this query repeated: SELECT "django_site"."id", "django_site"."domain", "django_site"."name" FROM "django_site" WHERE "django_site"."id" = 91 However, these are all in "idle" status. They don't seem to be deadlocked, as if I refresh the results, the pid for these idle queries is cleared in about a minute, but still, such a simple query should not be taking an entire minute to run. How do I debug the source of this terrible performance? I haven't changed my code or server configuration, so I'm assuming some package update introduced some change or bug. -
Does Django Channels 1 & 2 compatible on Redis backend level?
I have an legacy Django app that uses Channels v1 with Redis backend. The new app I'm creating uses Channels v2 and should communicate with legacy app. Can it be done via the same channel layer Redis backend? I mean, can the new app send a message to an old app channel and get a response back? -
How to save uploaded files to models and serve them in templates?
I've been following the django 2 official tutorial but I'm a bit confused as how to work with images and uploaded files. I have a project with a few apps. Let's call the project myProj and the app myApp. There is a model in myApp called myModel which has an image field myImage. Here is my model: from django.db import models class myModel(models.Model): myImage = models.ImageField(upload_to='myApp_images') Here is my template: <img src="{{ n.image }}"></img> Here is my view from django.shortcuts import get_object_or_404, render from .models import myModel def index(request): n = myModel.objects[0] context = { 'n': n, } return render(request, 'myModel/index.html', context) And here is my settings:(parts I thought were relevant) INSTALLED_APPS = [ 'news.apps.myModelConfig', 'django.contrib.staticfiles', ] MEDIA_URL = '/media/' MEDIA_ROOT = '/home/aran/myfiles/projects/futureCoin/media/' Here is my myProject/urls.py: from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('myModel/', include('myModel.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So I made an instance of the model through the django admin site. Here is the directory tree after that(I removed the pycache): . βββ myProject β βββ __init__.py β βββ models.py β βββ settings.py β βββ urls.py β βββ wsgi.py βββ manage.py βββ media β¦ -
'OSError: dlopen(libgdal.so, 6): image not found' in Django Project from GDAL
had to replace my macbook (hd failure) and am now trying to setup a Django (1.11.9) project on a new machine running High Sierra 10.13.4. running into this PATH err I haven't seen before (I could setup and run project successfully on previous machine w/ same pyenv env, version and dependencies). Per this thread it may be a SIP issue with lack of permissions to /usr/lib on newer machine. When I run any manage.py command (manage.py makemigrations, manage.py migrate, manage.py runserver, etc.) project throws this err: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/auth/base_user.py", β¦ -
Django AdminDateWidget does not select the date from the calendar on click
There have been lots of queries related to this topic. But I am still not been able to use AdminDateWidget successfully. Here are my code details: forms.py is as follows : class SelectDay(forms.Form) : dayCh = DateField(widget=AdminDateWidget()) My template file contains the following : <head> {% load static %} {% block extrahead %} <script type="text/javascript" src="/admin/jsi18n/"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> <script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"> </script> <script type="text/javascript" src="/static/admin/js/jquery.min.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/actions.min.js"></script> <script type="text/javascript" src="/static/admin/js/calendar.js"></script> <script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'admin/css/base.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'admin/css/widgets.css' %}"/> {% endblock %} </head> When I execute, the screen looks as follows : which is how I want. But the problem is that when I choose a date from the calendar, the date is not selected. On the other hand when I select Today the correct date gets selected. Also from the calendar Yesterday, Today and Tomorrow are getting selected. Please guide. -
Get passed in 4 argument but read as 5 by Django server
I encounter such a unexpected error when use model User TypeError at /user/register create_user() takes from 2 to 4 positional arguments but 5 were given Request Method: POST Request URL: http://127.0.0.1:8001/user/register Django Version: 1.11.13 Exception Type: TypeError Exception Value: create_user() takes from 2 to 4 positional arguments but 5 were given Actually, I do provide 4 arguments rather than 5 def register(request): if request.method == "GET": form = UserForm() if request.method == "POST": form = UserForm(request.POST) print(vars(form)) if form.is_valid(): user = User.objects.create_user( form.cleaned_data['first_name'], form.cleaned_data['last_name'], form.cleaned_data['email'], form.cleaned_data['password']) user.save() redirect("article/index.html") and the forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', "email", "password" What's the problem it might be? -
Why isn't Django unit test isn't seeing a raised exception?j
I'm trying to test a static method in one of my models but the test is not seeing an exception that's being raised and I don't understand why. Here's the model and static method: # models.py class List(models.Model): owner = models.ForeignKey(User) type = models.ForeignKey('ListType', help_text=_('Type of list')) name = models.CharField(_('list'), max_length=128, help_text=_('Name of list')) class ListType(models.Model): type = models.CharField(_('type'), max_length=16) @staticmethod def read_list(list_id, list_name, owner, list_type): try: return List.objects.get(pk=list_id, name=list_name, owner=owner, type=list_type) except List.DoesNotExist: return None Here's the test: # tests.py from django.test import TestCase from .factories import * from .models import List, ListType class TestFuncs(TestCase): def test_read_list_exc(self): with self.assertRaises(List.DoesNotExist): uf = UserFactory() lt = ListType.objects.get(type='Member') lf = ListFactory(owner=uf, type=lt, name='foo') # I've created one list but its name isn't 'bar' list = List.read_list(999, 'bar', uf, lt) If I set a debugging breakpoint in the read_list method and run the test, I do see the exception being raised: # set_trace output: (<class 'list.models.DoesNotExist'>, DoesNotExist('List matching query does not exist.',)) # test output: ... File "...." list = List.read_list(999, 'bar', uf, lt) AssertionError: DoesNotExist not raised I've read other questions here about how to detect this type of exception and I thought I was doing it right. Just for fun, I β¦ -
How to use WhatsApp to deliver notifications instead of Plain Old SMS Notifications like this?
I want to deliver notifications from my Django server to user's WhatsApp if it exists. Something like in this image: A startup (Swiggy) using Whatsapp to deliver notifications There are some other travel companies also using this to deliver pdf files (ticket) in whatsapp chat directly instead of the mail. Can any one guide or can give some idea on how to achieve this? -
How effectively start python-Django developement?
I know python, But I am new to python-development, I want to learn python-Django. I have read the Django in Tutorials point also. Currently, I am trying to understand the logic from this link (https://github.com/mrsarm/django-coleman). Please suggest me where I have to start to learn python-Django more effectively?. Should I learn it from scratch or learn it from any Django book or any useful websites?. -
Use a custom generated string as a model field value in django
I want to search a keyword in multiple (about 20) forum-user databases. Unfortunately, the specific tables are named differently throughout the databases. In one database, the user-table is named username, in another it is named name etc. I added a model field field_username to every forum field_username which saves the corresponding value of each database. {% for key, value in forum.items %} <p>{{ value.field_username }}</p> {% endfor %} <p>{{ user.customUsername }}</p> I then want to use that customUsername as a model field value like this: {% for user in value.user_list %} <p>{{ user.customUsername }}</p> {% endfor %} ... so that customUsername evaluates to the database value, like username, name, display_name etc. Right now, nothing happens. Is that possible? -
Angular 5 Django CSRF token
I am trying to do a simple login page with the Django Rest Framework and I keep getting a csrf token error. To get around this for now, I have appended the @csrf_exempt annotation on my login method which works but is unsecure. This is my method: @csrf_exempt def login(request): print(request.COOKIES) username = request.POST.get('username') password = request.POST.get('password') print("username {} password {}".format(username, password)) user = authenticate(request, username=username, password=password) group = None if user is not None: django_login(request, user) request.session.set_expiry(0) result = True status = 200 else: result = False status = 401 data = {'result': result, 'username': username} return HttpResponse(json.dumps(data), content_type="application/json", status=status) My Rest Framework Settings: REST_FRAMEWORK = { 'DATETIME_FORMAT': "%m/%d/%Y %H:%M:%S", 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework.filters.SearchFilter', 'django_filters.rest_framework.DjangoFilterBackend', ), 'EXCEPTION_HANDLER': 'common.custom_exception_handler.custom_exception_handler' } Without the csrf_exempt annotation, I get Forbidden (CSRF token missing or incorrect.): /authentication/login however, when I print the cookies I actually get a token in my cookie. {'csrftoken': 'HZc8vPqoad...7eIvTzep', 'sessionid': 'n71c....g5c7'} gets printed when I add the @csrf_exempt annotation back in. In my angular code, I have also tried to attach the csrf token as a request header with 'X-CSRFToken' but I noticed two things 1) in my request, the X-CSRFToken i obtain from document.cookies is NOT β¦