Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
image in django won't upload via form
I already found many answers to that question but most of them refer to adding request.FILES wchich doesn't work for me. I can upload an image via admin page, but when it comes to form i am getting an error that image is not loaded (while it is) Here is my model class Player(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=30) position = models.ForeignKey(Position,on_delete=models.CASCADE) shirt_number = models.IntegerField() team = models.ForeignKey(Team,null=True,on_delete=models.SET_NULL) image = models.ImageField(upload_to='images/players/') Here is my form class PlayerForm(forms.ModelForm): class Meta: model = Player exclude = ('team',) Here is views.py def team_detail(request,slug): team = get_object_or_404(Team, slug=slug) players = Player.objects.filter(team_id=team.id) if request.method == "POST": form = PlayerForm(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('') else: form = PlayerForm() return render(request,'team_detail.html',{'team':team,'players':players,'form':form}) And here is template file <form method = "POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="SUBMIT"> </form> Before submitting After pressing submit button -
How to use prefetch_related in many to many relation django rest framework
I have some models (models.py): class User(models.Model): username = models.CharField(max_length=250) fullname = models.CharField(max_length=250) class Permission(models.Model): name = models.CharField(max_length=250) class User_Permission(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) permission = models.ForeignKey(Permission, on_delete=models.CASCADE) views.py class User_View(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = User_Serializer I want to optimize api. How can I use prefetch_related there? I set related name to UserPermission model and User.objects.prefetch_related('related_name'). But queries are not optimized -
Django get data from ForeignKey models
I have a simple models with a ForeignKey models, I am trying to get data from the ForeignKey models and display them on a HTML file. I tried this but it give me an error 'QuerySet' object has no attribute 'AccountHistory' #Get AccountHistory ForeigKey Models data = Account.objects.all() test_trade = data.AccountHistory.all(pk=account_id) models.py class Account(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) accountid = models.CharField(max_length=100) def __str__(self): return self.accountid class AccountHistory(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) tradeid = models.CharField(max_length=100) profit = models.FloatField() def __str__(self): return self.tradeid views.py def metrix(requets, account_id): if requets.user.id: # Get Account models data item = Account.objects.get(pk=account_id) #Get AccountHistory ForeigKey Models data = Account.objects.all() test_trade = data.AccountHistory.all(pk=account_id) context = { "test_trade": test_trade, "item": item, } return render(requets, "main/metrix.html", context) return render(requets, "main/testpage2.html") metrix.html <div class="container"> {% for tradeinfo in test_trade %} <div class="TradeHistoryTable"> <table class="table table-dark"> <thead> <tr> <th scope="col">TradeID</th> <th scope="col">OpenDate</th> </tr> </thead> <tbody> <tr> <td>{{tradeinfo.tradeid}}</td> <td>{{tradeinfo.opendate}}</td> <td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> -
How can I break up a Django request into multiple requests?
I wanna do the following inside a Django REST ModelViewSet: receive data from an HTTP POST request break the data into several pieces pass the pieces to different ViewSets that should handle authentication, etc. based on the original request Background is the following: I have a working REST implementation with normal ModelViewSets for all endpoints and now I'm implementing a syncing protocol for a Progressive Web App that should work completely offline. The idea is that the normal ViewSets keep working and I implement the custom logic only once in the ViewSets. But I want to be able to collect request data offline and send all at once (also to guarantee order). Then the "sync" endpoint breaks the data apart and passes it to the respective views. I'm only missing a copy of the request object with adjusted data... What I tried to far: deepcopy of the request object does not work I have a hard time figuring out how to construct a request from scratch that mimics the original -
problem when try to make ajax request with django
i have a problem when make ajax request to the server to add product to the card using django and jquery, this the URLs here: path('add_to_cart/', cartView.add_to_cart, name="add_to_cart") here the jquery code: $(document).ready(function () { $('.addToCartBtn').click(function (e) { console.log("jjjj") e.preventDefault(); var product_id = $(this).closest('.product_data').find('.prod_id').val() var product_qty = $(this).closest('.product_data').find('.qty-input').val() var token = $('input[name=csrfmiddlewaretoken]').val() console.log(token) console.log(product_id) console.log(product_qty) $.ajax({ method: 'POST', url: 'add_to_cart', data: { 'product_id' : product_id, 'product_qty' : product_qty, csrfmiddlewaretoken: token }, success: function(res) { console.log(res.status) alertify.success(res.status) } }) }) }); and here is the view django code: from django.http.response import JsonResponse from django.shortcuts import render, redirect from django.contrib import messages from store.models import Product, Cart def add_to_cart(request): if request.method == 'POST': if request.user.is_authenticated: prod_id = request.POST.get('product_id') product_check = Product.objects.get(id=prod_id) if product_check: if Cart.objects.filter(user=request.user.id, product_id=prod_id): return JsonResponse({'status': 'Product Already in the Cart'}) else: prod_qty = int(request.POST.get('product_qty')) if product_check.quantity >= prod_qty: Cart.objects.create(user=request.user, product_id=prod_id, product_quantity=prod_qty) return JsonResponse({'status': 'Product Added Successfully'}) else: return JsonResponse({'status': "only" + str(product_check.quantity) + "is Available"}) else: return JsonResponse({'status': 'No Such Product Found'}) else: return JsonResponse({'status': 'Login To Continue'}) return redirect('/') and here is the view.html when add to card button exist: <section style="background-color: #eee;"> {% csrf_token %} <div class="container py-5 product_data"> <div class="row justify-content-center mb-3"> <div class="col-md-12 col-xl-10"> <div … -
How to auto update a models attribute on creation of another model
I have been learning django and django rest from several different courses and have started my own project which will be a forum type web application. I 4 model classes Category, SubCategory, Thread, and Post. What I want to be able to do is have an attribute for subcategory called num_threads that can be updated when ever a thread is made for the subcategory it is related to. Similarly I will want a thread to have attributes num_posts and num_views. I have been using foreign keys to relate the models. Now I am not sure that I am doing that part correctly. Here is my model.py: from django.db import models from django.contrib.auth.models import User class Category(models.Model): """ Category Class: Main Categories for GRDG Forum Creation and Deletion will be restricted to site admin """ # Attributes name = models.CharField(max_length=32, unique=True, blank=False) description = models.TextField(max_length=150, blank=True) def __str__(self): return self.name class SubCategory(models.Model): """ SubCategory Class: SubCategories will be one to many relation with category ie: Multiple subcategories related to one category Creation and Deletion will be restricted to site admin GET methods restriction will vary by subcategory """ # References category = models.ForeignKey(Category, on_delete=models.CASCADE) # Attributes name = models.CharField(max_length=32, unique=True, blank=False) … -
Django and Python logging what is the full dictionary for the formatter?
Apologies if the title is vague. Feel free to edit to include the correct terminology. In settings.py, I have the LOGGING dictionary with this formatter: 'formatters': { 'standard': { 'format': '{asctime} {message}', 'style' : '{', } I understand that asctime is the time that the log message was generated, and message is the message itself. But I don't know what other options are available. Is the message itself a Python dictionary, and the curly-braced items are keys in the dict? How can I view all keys in that dictionary? I assume {severity} is in there somewhere. What else can I enter? Also, what are the various options under 'style'? -
Input object to django database without user input
So i want to input objects in my django database based on a list of objects. How would i move forward with this? Doing it with user input works. A workaround could maybe be to set the user input fields based on a list of objects and then POST that form but it seems dirty. Any thoughts? :) -
Exception Value: Field 'id' expected a number but got ''. (Django)
I was trying to code an add photo page on Django but got an error. I was watching this video on youtube to write my own project. I already wrote python manage.py makemigrations and then python manage.py migrate. Unfortunately, it did not work. Here is the "view.py" file: def addPhoto(request): categories = Category.objects.all() if request.method == 'POST': data = request.POST image = request.FILES.get('image') if data['category'] != 'none': category = Category.objects.get(id = data['category']) else: category = None photo = Photo.objects.create( title=Title, category=category, description=data['description'], image=image, ) return redirect('index') context = {'categories':categories} return render(request, 'auctions/newlisting.html', context) Here is the "urls.py" file: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("newlisting", views.addPhoto, name="create_listing"), path('photo/<str:pk>/', views.viewPhoto, name='photo'), ] Here is the "models.py" file: class Category(models.Model): category = models.CharField(max_length = 30) def __str__(self): return f'{self.category}' class Photo(models.Model): class Meta: verbose_name = 'Photo' verbose_name_plural = 'Photos' title = models.CharField(max_length = 60,) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False) description = models.TextField() def __str__(self): return self.description Here is the "newlisting.html" file: {% extends "auctions/layout.html" %} {% block body %} <div class="m-5"> <div class="container"> <div class="row justify-content-center"> <div class="col-md-6"> <h2>Create Listing</h2> … -
Any beginner friendly tutorial to integrate D3js with django?
I am looking for a tutorial (beginner friendly) to integrate D3js with Django. My objective is to display graphs on my django website using sqlite database. I found very few tutorial on this topic but they are beyond my level. Thanks. -
update foreignkey field in Django
have the following models Class FootballWebsite(models.Model): """Football service website.""" url = models.URLField(validators=[validate_club_url], unique=True) #Football service id = models.CharField(primary_key=True, unique=True) sub_categories = models.ForeignKey(SubCategory, default=1) class SubCategory(models.Model): """Sub Category""" category = models.ForeignKey(Category) name = models.CharField(max_length=50) slug = models.SlugField() and trying to execute the following class Command(BaseCommand): def handle(self, *args, **options): websites = FootballWebsiteDescription.objects.filter(title__in=['title1',' title2']) for website in websites: try: fc = FootballWebsite.objects.filter(id=website.about_id).update(sub_categories_id=88) fc.sub_categories_id = 88 fc.save() and also the following option fc = FootballWebsite.objects.filter(id=website.about_id).update(sub_categories_id=88) to my understanding both ways to update the subcategory id from the default 1 to 88 should work. i can update other fields this way at least, and see this as an example referenced anywhere. i can only find this reference Django: Set foreign key using integer? which indicates i might have run into a bug in my very old Django 1.7 project. Am i missing something very obvious here or is there a work around? much obliged. -
Django: How to customize display based on the logged in user
creating an attendance system where lecturers register and login using their lecturer code and password different lecturers teach different subjects, as such i would like the "subject" page to display only the subjects taught by the specific lecturer currently, the "subject" page displays all subjects present in the database how can i do that? [Source code][1] [1]: https://github.com/Zainab692/Fyp2 -
Checking for data in the database and re-requesting a third-party API
I'm using Django Rest Framework for the following task (I'll write it in detail so that everything is clear): The service must implement a REST API that accepts POST requests as input with content like {"questions_num": integer} . This item is done. After receiving the request, the service, in turn, requests the number of questions specified in the received request from the public API (English questions for quizzes) https://jservice.io/api/random?count=questions_num. This is also done. Further, the received answers should be stored in the database (or Postgres or Sqlite) fields from the quiz: 1. Question ID, 2. Question text, 3. Answer text, 4. - Question creation date. This is also done. And it's not clear how to normally do the following moment: In the event that the database has the same question, additional requests must be made to the public API with quizzes until a unique question for the quiz is obtained. It turned out to be a crutch, but I would like it to be beautiful, or at least normal. Tell me how to implement this? Thanks in advance. -
Could not import 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
Full Error: Could not import 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'smart_text' from 'django.utils.encoding' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } And this is the pip freeze in the virtual env: (backend) PS D:\js\backend> pip freeze asgiref==3.5.1 Django==4.0.4 django-cors-headers==3.11.0 djangorestframework==3.13.1 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==5.1.0 mysqlclient==2.1.0 PyJWT==1.7.1 pytz==2022.1 sqlparse==0.4.2 tzdata==2022.1 in the middle of the error, it addresses some lines across views.py for decorators: from http.client import HTTPResponse from multiprocessing import context from django.shortcuts import render from django.http import HttpResponse, Http404, JsonResponse from .models import Tweet from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework.decorators import api_view, permission_classes from rest_framework import status I'm not sure if they're even related -
Export a table from sqlite db in excel/csv file using python, django
How can I export a table from my sqlite db, using python, in to a excel or csv file? -
Change renderer class inside custom pagination in django rest framework
I am using custom renderer class by default in settings.py. For api I check query parameter "page", if it exist then I paginate result else response using default renderer class. But I have problem, I want to use JSONResponse renderer for pagination settings.py REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'app.core.renderers.CustomJSONRenderer', "rest_framework.renderers.JSONRenderer", "rest_framework.renderers.BrowsableAPIRenderer", ), } renderers.py class CustomJSONRenderer(JSONRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): status_code = renderer_context['response'].status_code response = { "success": True, "message": None, "data": data, } return super(CustomJSONRenderer, self).render(response, accepted_media_type, renderer_context) views.py class User_View(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = User_Serializer pagination_class = CustomPagination pagination.py class CustomPagination(PageNumberPagination): page_size_query_param = 'size' page_size = int(settings.PAGE_SIZE) renderer_class = [JSONRenderer] def get_paginated_response(self, data): return Response({ 'success': True, 'total': self.page.paginator.count, 'page_size': self.get_page_size(self.request), 'current_page': self.page.number, 'last_page': self.page.paginator.num_pages, 'data': data, }) wrong response: { "success": true, "message": null, "data": { "success": true, "total": 6, "page_size": 15, "current_page": 1, "last_page": 1, "data": [ { "id": 1, "username": "admin", "permissions": [] } ] } } Correct response (expected): { "success": true, "total": 6, "page_size": 15, "current_page": 1, "last_page": 1, "data": [ { "id": 1, "username": "admin", "permissions": [] } ] } How can I fix it? -
Why do I get an error message while adding a html page to Django if I put everything in urls.py and views.py?
I am trying to finish this Django project, but I am having difficulty adding a html page. I added all the necessary code to views.py, urls.py, and base.html, but I am still unable to successfully add the html. I will add screenshots of my files below, if anyone can help. views.py main.html base.html urls.py error message in terminal (last line) -
Response time increasing with time Spring-Boot application?
This is my first question. I am a beginner in Backend development. So, in case I haven't mentioned my problem correctly or you want more information around the problem, please ask, I will learn. We have our backend in Python-Django monolithic architecture, which we are planning to shift to Spring-boot micro-services. The database we are using is Postgres. I started it by shifting the critical GET APIs first of our existing code, i.e. POST and PATCH requests are handled by the Django application independently, but the GET requests are handled by Spring-Boot. So, I have re-routed the GET API call on Python-Django to Spring boot microservice, using Requests HTTP Library and added a fall back again to Python-Django code if the requests.status_code is not 200 from Spring-Boot Application Python Rerouting code snippet : SPRING_URL = SPRING_MICROSERVICE_URL + "/users/sent/{user_id}/" response = requests.get( url=SPRING_URL.format(user_id=self.request.user.id), params=payload ) if response.status_code == 200: return self.get_response(data=response.json()) else fallback to the existing python-django code There are 6-7 DB calls, out of which only 1 is time-consuming on a Materialized View PSQL, which takes around 1sec for some of the requests in my local and staging machines. I am using HikariCP for connection pooling. Now, when I am … -
Is there a way to open a template using a modal in django?
I'm new to django and web development in general, and would like to know if there is a way to show an already existing html template when triggering a modal pop-up, which would be done by clicking an icon. I've read the docs in the materialize site, but they only showed how to create a modal from scratch. I'd really appreciate some help. Idk if it is necessary, but here is the code I'm using to open the template when I click the icon: @admin.display(description='Visualizar') def get_view(self): url = ( f"<a href='/transparencia/visualizar/{self.id}/' target='_blank'><i class='tiny material-icons'>search</i></a>" ) return format_html(url) -
Annotate every obj of QuerySet with count of every choice of related obj's, grouped by choice value
Let's say I have two models: class Mailing(models.Model): ... class Message(models.Model): date_created = models.DateTimeField(default=aware_utc_now) class DeliveryStatusChoices(models.TextChoices): # Number of choices may vary. PENDING = 'pending' SUCCESS = 'success' FAIL = 'fail' status = models.CharField( choices=DeliveryStatusChoices.choices, default=DeliveryStatusChoices.PENDING, max_length=50 ) mailing = models.ForeignKey( 'Mailing', on_delete=models.CASCADE, related_name='messages' ) I'm looking for a way to annotate mailings with count of related messages grouped by choice value. To be able to do something like: mailing.stats and get: {'pending': 15, 'success': 20, 'fail': 2} Only messages related to particular mailing should be counted. I found out how to get stats for particular mailing: models.Message.objects.filter(mailing_id=1).values('status').annotate(count=Count('status')) the output is: <QuerySet [{'status': 'pending', 'count': 5}, {'status': 'success', 'count': 2}, {'status': 'fail', 'count': 3}]> annotate cannot be called on particular object. So, for loop won't work. Also output format is not as desired. But it's ok. Another way I found: result = [] for mailing in models.Mailing.objects.all(): statuses = mailing.messages.values('status').annotate(count=Count('status')) mailing_result = {'id': mailing.id} for status in statuses: mailing_result[status['status']] = status['count'] result.append(mailing_result) But this solution gives me just list of dicts. Sometimes I have to prefetch related objects based on some criteria: messages = Prefetch( 'messages', models.Message.objects.filter( date_created__gte=yesterday_midnight, date_created__lt=today_midnight ) ) mailings = models.Mailing.objects.prefetch_related(messages) In this case I'd like to … -
Filtering by custom UUIDField got broken with Django 3.2 upgrade
I have a Django project that I've recently upgraded from Django 2.2 to 3.2. In this project, I use a custom UUIDField that saves UUIDs to MySQL as char(36) in the following format: 12345678-1234-5678-1234-567812345678. import uuid from django.db import models class UUIDField(models.UUIDField): """ Overrides Django UUIDField to store full UUID's including dashes. """ def __init__(self, verbose_name=None, **kwargs): super().__init__(verbose_name, **kwargs) self.max_length = 36 def get_internal_type(self): return "CharField" def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None if not isinstance(value, uuid.UUID): try: value = uuid.UUID(value) except AttributeError: raise TypeError(self.error_messages['invalid'] % {'value': value}) if connection.features.has_native_uuid_field: return value return str(value) After the upgrade, I noticed that searching for full UUIDs didn't work anymore. If I only provide the first part of the UUID (up to the first character after the first hyphen) it works as expected. Python 3.6.9 (default, Mar 15 2022, 13:55:28) [GCC 8.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from foobar.foo.models import Foo >>> >>> Foo.objects.all() <QuerySet [<Foo: Foo object (34c46fe8-caf0-11ec-bdb9-482ae362a4c0)>]> >>> >>> Foo.objects.filter(id__icontains='34c46fe8-caf0-11ec-bdb9-482ae362a4c0') <QuerySet []> >>> >>> Foo.objects.filter(id__icontains='34c46fe8-') <QuerySet [<Foo: Foo object (34c46fe8-caf0-11ec-bdb9-482ae362a4c0)>]> >>> >>> Foo.objects.filter(id__icontains='34c46fe8-c') <QuerySet []> >>> I've played with the UUIDField methods, but I can't seem to figure out … -
Render stl files stored in django app with Blender
I'm a beginner on python and blender, and, as my technical expertise is not quite good, I will try to explain as simple as I can. At first i'm using Django framework to build a simple app where i have a form used to upload stl files (file.stl). After uploading i would like to click the stl file from django app and open it in blender GUI app. Is this possible? If possible could you please give me some hints on how to start, any docs or tutorials. Thanks in advance! -
How can i put all the months in a Month attribute?
input = [ { "Year": "2019", "Month": "06", "Days_Past_Due": "450", "Asset_Classification": "?" }, { "Year": "2019", "Month": "05", "Days_Past_Due": "50", "Asset_Classification": "?" }, "Year": "2019", "Month": "12", "Days_Past_Due": "10", "Asset_Classification": "?" } ] output = [{ "year": "2019", "description": "Days Past Due", "dec": "10", "nov": "0", "oct": "0", "sep": "0", "aug": "0", "jul": "0", "jun": "450", "may": "50", "apr": "0", "mar": "0", "feb": "0", "jan": "0"}] -
How can I automatically generate unique 4 digits and save in Django Model
I am working on a project in Django where I have a SubmitedApps Model which is intended for all submitted applications. Below is the model code: class SubmitedApps(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) confirm = models.BooleanField() date = models.DateTimeField(auto_now_add=True) def __init__(self): super(SubmitedApps, self).__init__() self.application = str(uuid.uuid4()) def __unicode__(self): return self.applicant def __str__(self): return f'Application Number: {self.application} Username:{self.applicant}' I also have a ModelForm which is a checkbox as shown below: class ConfirmForm(forms.ModelForm): confirm = forms.BooleanField() class Meta: model = SubmitedApps fields = ['confirm'] In the views.py I have try to check if the application was already submitted, and if not it should be submitted else it should redirect the applicant to Application Print Out Slip Page as shown below: @login_required(login_url='user-login') def SubmitApp(request): try: #Grab the logged in applicant in the submited app table check_submited = SubmitedApps.objects.get(applicant=request.user) #If it Does NOT Exist then submit it except SubmitedApps.DoesNotExist: if request.method == 'POST': submit_form = ConfirmForm(request.POST, request.FILES) if submit_form.is_valid(): submit_form.instance.applicant = request.user submit_form.save() messages.success(request, 'WASU 2022 Scholarship Application Submited Successfully') return redirect('app-slip') else: submit_form = ConfirmForm() context = { 'submit_form':submit_form, } return render(request, 'user/confirmation.html', context) else: if check_submited.application != "": return redirect('app-slip') My problem his … -
How to customise the default_user_authentication_rule in Django Rest Framework
I want to customize the default_user_authentication_rule used by simple jwt authentication. The usual process that it follows is that it checks if the user account for which it has received the credentials is active or not. If is_active is true then it goes on with the authentication else it throws the Unauthorised error. I want to customise this function so that I get the Unauthorised error only when the user account does not exist at all or the credentials are invalid. If the user exists and is_active = False I want to return something like not-active so I can do something with it I have planned. Please suggest to me what should I do as I have found no documentation regarding the same. Below is the Simple JWT settings SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=3), 'REFRESH_TOKEN_LIFETIME': timedelta(days=7), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', # this is what I was talking about 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), }