Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting "GET /user HTTP/1.1" 401 28 in django development server
When I login in my reactjs i get jwt token but at backend didn't recieve the token is empty it execute this part of code and after printing token token = request.COOKIES.get('jwt') None is printed why I am not getting the cooking in backend. since i got cookies in my browser after i login cookies:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NywiZXhwIjoxNjkzMjQ3NDA3LCJpYXQiOjE2OTMyNDM4MDd9.SPecH4BsNh76EjTHMoSDzWfaT8dt8KhnfNYKx8qQ0OU Django code print(token) if not token: print("dint get token") raise AuthenticationFailed('Unauthenticated') `class UserView(APIView): # permission_classes = [AllowAny] def get(self, request): token = request.COOKIES.get('jwt') print(token) if not token: print("dint get token") raise AuthenticationFailed('Unauthenticated') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user = User.objects.filter(id=payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data)` reactjs code `import jwtDecode from 'jwt-decode'; import { useState,useEffect } from 'react'; const HomePage = () => { const [name, setName] = useState(''); useEffect(() => { ( async () => { const response = await fetch('http://127.0.0.1:8000/user', { headers: { 'Content-Type': 'application/json' }, credentials: 'include', }); if (response.ok) { const content = await response.json(); setName(content.name); console.log(name); const cookies = document.cookie; const token = cookies.split(';')[0].split('=')[1]; const decodedToken = jwtDecode(token); console.log(decodedToken); } else { console.log('Error fetching user data'); } } )(); }, [fetch]); return ( <div> <h1>hi {name}</h1> </div> ); }; export default HomePage;` ` django backend didn't … -
DoesNotExist at / No exception message supplied in Django
I'm encountering a DoesNotExist exception when using the provider_login_url template tag from the allauth library in my Django project. The issue occurs on the signup.html template in the section where I'm using this tag. Despite trying various solutions, I'm unable to resolve this error. Error Details: When I access the homepage of my Django application (http://127.0.0.1:8000/), I encounter a DoesNotExist exception with no specific exception message. The traceback points to the usage of the provider_login_url template tag on line 166 of the signup.html template. <body> <div class="background"> <div class="shape"></div> <div class="shape"></div> </div> <form method="POST"> {% csrf_token %} <h3>Signup Here</h3> <label for="username">Username</label> <input type="text" placeholder="Username" name="username" id="username"> <label for="email">Email</label> <input type="email" placeholder="Email or Phone" name="email" id="email"> <label for="password1">Password</label> <input type="password" placeholder="Password" id="password1" name="passwd"> <label for="password2">Confrom Password</label> <input type="password" placeholder="Confrom Password" id="password2" name="cpasswd"> <button type="submit">Signup</button> <a href="{% url 'login' %}" >i have already account</a> </form> 165 <h2>Google Account</h2> 166 <a href="{% provider_login_url 'google' %}?next=/">Login With Google</a> </body> Configuration Details: Django Version: 4.2.4 Python Version: 3.11.4 Installed Applications: django.contrib.auth django.contrib.sites allauth allauth.account allauth.socialaccount allauth.socialaccount.providers.google Steps Taken: Checked for extra whitespace around the provider_login_url template tag. Ensured proper configuration of the Google social application in Django admin. Verified the correctness of the Google API … -
Looking for a monorepo system to handle it all
I am currently working on X repositories. We would like to refine everything at work to use them within a monorepo. But here comes the point. The repositories include JavaScript (NodeJS, NextJs, ReactJs) [including TypeScript], a Django backend written in Python, and serverless functions. The JS parts are not the big problem. Here I use npm (we would change to pnpm) as package manager and VITE as bundler. My biggest problem is the Python part. We use pip currently and use a "requirement.txt" for the dependencies. I have already seen Nx and tried it. But the python plugin uses poetry . I can get it to work. But my boss doesn't want to switch to poetry unless it's absolutely necessary. Is there a monorepo that I can use without switching to poetry? Additionally, we want to upgrade to python 3.11. Otherwise there is a monorepo system which meets the requirements? Hours and hours of research -
why wont the template i am calling show up when i set my form to "crispy"
i have a django project with a login page i have called register.html i have created a directory in my project called users and keeping with django another directory named users and a sub-directory template->users->register: my_project/ ├── my_project/ │ ├── ... │ ├── users/ │ ├── templates/ │ │ ├── users/ │ │ │ ├── register.html │ └── ... the code for the page is as follow: {% load crispy_forms_tags %} <!DOCTYPE html> <html> <head> <meta name="description" content="Welcome to our text messaging campaigning website"> <title>R&D Texting</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>hi</h1> </header> <div class="content-section"> <form method="POST"> {% comment %} Do not remove the csrf token! {% endcomment %} {% csrf_token %} <fieldset class = "form-group"> <legend class ="border-bottom mb-4">Join today</legend> {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already have an account?<a class ="ml-2" href="#">Sign in</a>" </small> </div> </div> </body> </html> when i run this code(with the proper urls and paths etc) i get a 404 page saying it cant find the template when i remove the "|crispy" everything runs fine. my rendering request form views etc seem to be find however the crispy template cant be found(i have made sure … -
uploading an image api in django return null
my models class Slider(models.Model): image = models.ImageField(upload_to="images/") description = models.TextField() my views class UploadImage(viewsets.ModelViewSet): queryset = Slider.objects.all() serializer_class = SliderSerializer parser_classes = (MultiPartParser, FormParser) def perform_create(self, request, *args, **kwargs): try: file = request.data["image"] title = request.data['description'] except KeyError: raise ParseError('Request has no resource file attached') Slider.objects.create(image=file, description=title) serializers class SliderSerializer(serializers.ModelSerializer): class Meta: model = Slider fields = '__all__' urls urlpatterns = [ path('api/upload', views.UploadImage.as_view({'post': 'create'}), name='home') ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) json Hello I Wrote an API for uploading image in Django but unfortunately it didn't work and when I upload an image it return null and I don't know why. I appreciate if you help me. Thank you. -
How to add an editable field in the django admin that is not directly linked to a model field?
How to add a custom editable field in the django admin and then transform it before storing it in a field in the model? Given this Model: import json from django.db import models from django.core.serializers.json import DjangoJSONEncoder class Foo(models.Model): _encrypted_data = models.TextField(null=True, blank=True) @property def data(self): encrypted = self._encrypted_data if not encrypted: return {} return json.loads(decrypt(encrypted)) @data.setter def data(self, value): if not value: self._encrypted_data = {} return self._encrypted_data = encrypt( json.dumps(value, cls=DjangoJSONEncoder) ) The field Model._encrypted_data contains encrypted data. The property Model.data makes it easy to work with the decrypted data in the code: encrypt/decrypt automatically. I am looking for an editable admin field that represents the Model.data property. I started to explore a custom Admin Form but I am not sure how to pass the decrypted data to the field and then save it on the model. class FooAdminForm(forms.ModelForm): class Meta: model = Foo fields = '__all__' data = forms.JSONField(label='Data', required=False) class FooAdmin(admin.ModelAdmin): form = FooAdminForm -
FileField in Django does not send file to its form request
I have a Django form where I upload an image through an input type file. class Form(forms.Form): photo = forms.FileField( label="Photo", widget=forms.FileInput( attrs={ 'class': 'form-control', } ) ) I wrote the next view: def upload(request): context = {} if 'photo' in request.POST: form = Form(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES["photo"]) else: print(form.errors) else: form = Form() context['form'] = form return render(request, 'app/upload.html', context) def handle_uploaded_file(file): with open('app/upload/'+file.name, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) When I send the form the request does not recieve any file, even if I loaded a file before. I am able to show by javascript jpeg files loaded when the field has changed. So the field is loading files but is not sending theme in the request. Form does not check the validation form.is_valid(): it says it is required even when I have uploaded a file .jpeg Error shown in print(form.errors): <ul class="errorlist"><li>photo<ul class="errorlist"><li>This field is required.</li></ul></li></ul> I leave my template form here: <form action="" method="post" id="search_face_form" style="width: 100%;"> {% csrf_token %} <div class="row"> <div class="col-sm-4"> <div class="input-group-sm mb-4"> <label for="floatingInput">Archivo de búsqueda</label> {{ search_form.face }} {{ search_form.face.errors }} </div> </div> <div class="col-sm-6"> <img id="search_face_img" src="{% static 'cameras_admin/img/not_found.jpg' %}" style="display: none; max-height: 25vh;"> </div> <div … -
Confirming the Updated User Email address in Django with a Boolean
Am creating profile Update. It works fine and l can change the Username and the Email. But l would like to confirm the New submitted email by sending an otp or a verification link , so that a user can verify that email. I have been looking for the solution of doing it but l just found one post on Stackoverflow, whereby someone is suggesting that you can deactivate the user and send a confirmation email and then activate him or her again But am asking; ls it possible to create a model with a Boolean field and connect that model to a User model, so that l can set that Boolean field to send a verification code to User who changed his or her email Address? email_comfirm.py #email comfirm model class EmailComfirm(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) is_comfirmed=models.BooleanField(default=True) active_otp=models.CharField(max_lenght=8) If possible; How can l phrase that model and it's function? I would like to call that Boolean to check if the email is changed, and if changed, turns off or set false and process the verification link after confirming the email it sets true. is_comfirmed() = False Secondly; How am l going to confirm that email? To me l would like to … -
My test fails due to sending an invalid file
Initially I will show you my action in my view: def add_photo_to_object(self, request, object_id, pk=None): uploaded_file = request.data.get('image') print(uploaded_file.size) request.data['user_owner'] = request.user.id print(request.data) serializer = self.action_serializers['add_photo_to_object'](data=request.data) serializer.is_valid(raise_exception=True) serializer.save() ... The results of these prints are - 0 and <QueryDict: {'name': ['small'], 'image': [<InMemoryUploadedFile: mock_image.jpg (image/jpg)>], 'user_owner': [1]}> My test looks like this: def test_add_photo_to_object(authorized_client, objects): checkpoint = objects[0] questionnaire = checkpoint.element.first() url = reverse('checkpoint-add-photo-to-object', kwargs={'pk': checkpoint.id, 'object_id': object.id}) uploaded = SimpleUploadedFile('mock_image.jpg', b'mock_content' * 1000, content_type='image/jpg') photo_data = {"name": "small", "image":uploaded} response = authorized_client.post(url, data=photo_data, format='multipart') response_data = response.json() assert response.status_code == status.HTTP_201_CREATED, response_data Well I always end up getting the error that AssertionError: {'image': ['Sent file is empty.']}. Please advise me how to avoid this error and Mock image such send. I can't use Pillow or store the test image on the server -
--headless vs --headless=chrome vs --headless=new in Selenium
I'm learning Selenium with Django and Google Chrome. *I use Selenium 4.11.2. Then, I tested with --headless, --headless=chrome and --headless=new as shown below, then all work properly: from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser(LiveServerTestCase): def test_example(self): options = webdriver.ChromeOptions() options.add_argument("--headless") # Here driver = webdriver.Chrome(options=options) driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser(LiveServerTestCase): def test_example(self): options = webdriver.ChromeOptions() options.add_argument("--headless=chrome") # Here driver = webdriver.Chrome(options=options) driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser(LiveServerTestCase): def test_example(self): options = webdriver.ChromeOptions() options.add_argument("--headless=new") # Here driver = webdriver.Chrome(options=options) driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title My questions: What is the difference between --headless, --headless=chrome and --headless=new? Which should I use, --headless, --headless=chrome or --headless=new? -
How to insert placeholder in Django Admin text input
I've tried three methods, first as described in how-to-add-placeholder-text-to-a-django-admin-field and in the docs from django import forms class AppointmentAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): kwargs['widgets'] = { 'name': forms.TextInput(attrs={'placeholder': 'Type here'}) } return super().get_form(request, obj, **kwargs) Then the method described in django-add-placeholder-text-to-form-field, slightly altered to get around Python errors. class AppointmentAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) form.base_fields['customer'].widget.attrs["placeholder"] = "Type here" return form Finally, using formfield_overrides: class AppointmentAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: { "widget":forms.TextInput(attrs={'placeholder':'Type here'})}, } None of these are working. I must be overlooking something simple? The relevant portion of models.py: class Appointment(models.Model): customer = models.ForeignKey(Customer, blank=False, null=True, default=None, on_delete=models.CASCADE, related_name='appointments') -
how to write test in django to check code fallback behavior to the database from redis corectly?
I have a python-django code. the code take inscode as input and check the redis and return blong data. in case redis is down or no data in it code fallback to database and read data from there. then i write integration test for this code in pytest check behave of the code in multiple cases on of the cases is that i want to mock redis and raise an error to disable it and see code can fallback to database and return data and in end return data should assert equal with data i got from redis before. main code: class GetOrderBook(APIView): def get(self, request, format=None): # get parameters inscode = None if 'i' in request.GET: inscode = request.GET['i'] if inscode != None: try: #raise ('disabling redis!') r_handle = redis.Redis( redis connection) data = r_handle.get(inscode) if data != None: return Response(json.loads(data)) else: print('GetOrderBook: data not found in cache') except BaseException as err: print(err) orderbook = OrderBook.objects.filter( symbol__inscode=inscode).order_by('rownum') if len(orderbook) > 0: data = OrderBookSer(orderbook, many=True).data data_formatted = # here making bnew format for row in data: # new format return Response(data_formatted) else: return Response({'Bad Request': 'invalid input'}) return Response({'Bad Request': 'incomplete input data'},) and this is test for part … -
SSO authentication not working on cross-domain requests
I am trying to enable SSO on my website. The backend is on Django hosted on a different domain and frontend is on React on a different domain. The backend is making Djoser package to handle social authentication. The sessionId which I receive in the form set-cookie header is not getting saved in browser cookies even though Access-Control-Allow-Credentials is true due to which SSO is failing. The same is working if my backend and frontend are on the same domain. Is there any solution to this? I am expecting SSO authentication on cross domain architecture but it is failing because session Id is not getting saved in browser cookies even though Access-Control-Allow-Credentials were enabled. -
Azure mobile app service keep getting it's pyodbc library version change without any actions
We have a Django/React mobile app that is hosted in Azure with the an app service plan (python 3.8.17) on Linux. 2-3 times a week, it stops working because the version of the pyodbc changes without any action on our side. We need to log into the SSH and switch the library libmsodbcsql-17-10.so.4.1 to libmsodbcsql-17-10.so.2.1 and then everything comes back to normal. What can cause this issue ? We checked if it was planned maintenance or any other Azure service that took action of some sort but couldn't find anything. -
Django unittest. Extract pk of a created object using .post method
Im studying some Python courses and i've got a project fully dedicated to unittest and pytest. The problem I have here is that i use the client.post method to create a note. My reviewer asked me get the note i just created using its pk. Have no idea how to do it. This is the code i currently have : def test_user_can_create_notes(self): response = self.auth_another_author.post(URL_NOTES_ADD, data=self.form_data) self.assertRedirects(response, URL_NOTES_SUCCESS) self.assertTrue(Note.objects.filter( title=self.form_data['title'], text=self.form_data['text'], slug=self.form_data['slug']).exists()) So i need to get the note object by pk and then check with assertEqual if its fields match the self.form_data fields I also tried getting the freshly created object using get and filter by the slug field. But that did not convince my reviewer -
How To Change LDAP Variables?
I need to change django-auth-ldap variables such as AUTH_LDAP_URI with dynamic inputs from user. How do I manipulate these variables in the memory? I tried changing imported variables expecting library automatically detects it. -
IntegrityError FOREIGN KEY constraint failed [In django project ]
While adding user data in DB through a form I created I got this error integrity error at \add_emp and it says foreign key constraint failed I tried deleting dbsqlite3 files, migrations files, and pychache files but that did not work please tell me where I am wrong it's my first time getting this error. enter image description here This is shown after submitting This is the Models.py code from django.db import models # Create your models here. class Department(models.Model): name = models.CharField(max_length=100,null=True) location = models.CharField(max_length=100) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100,null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE) salary = models.IntegerField(default=0,null=True) bonus = models.IntegerField(default=0,null=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,null=True) hire_date = models.DateField(null=True) def __str__(self): return "%s %s %s" %(self.first_name, self.last_name, self.phone) This is the views .py code # Create your views here. def index (request): return render(request,"index.html") def all_emp (request): context={"emps":Employee.objects.all(),"roles":Role.objects.all(),"departments":Department.objects.all()} return render(request,"all_emp.html",context) def add_emp(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] salary = int(request.POST['salary']) bonus = int(request.POST['bonus']) phone = int(request.POST['phone']) dept = int(request.POST['dept']) role = int(request.POST['role']) new_emp = Employee(first_name= first_name, last_name=last_name, salary=salary, bonus=bonus, phone=phone, dept_id=dept,role_id=role,hire_date = datetime.now()) new_emp.save() return … -
Which Certificate Authorirties can issue an X.509 certificate for document signing in PEM format?
I am looking to build a custom document signing solution in my Django application using PyHanko. I want to use the certificates from a CA for this purposes. However majority of CAs that I reviewed either offer the complete document signing service or they provide certificate as tokens/Yubikey. Only Digicert is the provider that I could find which allows to download the certificate and then use it manually. Are there any other CAs that allow to download a dcoument signing cert in PEM etc format? -
How can I load Deep learning model only once so that the problem of loading the model every time while calling API in Django is reduced?
I am trying to load the heavy pretrained model which size is larger than 1 GB though API using Django. The model is loaded every time I call API which is time consuming. What can be the solution for this ? I was expecting to load model only once and can use methods while calling API. -
DRF doesnt populate field label when using source
So, I have some model with few fields I want to expose over REST API: class MyModel(models.Model): field1 = models.TextField(verbose_name="Field 1") field2 = models.TextField(verbose_name="Field 2") and have corresponding serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('field1', 'field2') This way it works fine: using GET I retrieve fields values, and using OPTIONS I retrieve secondary fields information (e.g. if the field is required, help text, and label) The problem is that I don't want to expose real fields name, and I want to use some other name instead, for example: field1 and secondField. For that I modify my serializer: class MySerializer(serializers.ModelSerializer): secondField = serializers.CharField(source='field2') class Meta: model = MyModel fields = ('field1', 'secondField') Now I receive correct values on GET, but fields labels are wrong on OPTIONS: for second field I receive "Secondfield" instead of "Field 2" How do I get correct field label when using source? -
django session (i can't carry the data to the next page)
once the login successful , it redirect to the whmcs page and show the success message too but it's not show the first name and last name of the user why ?? please help me viewa.py ( `def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] api_url = 'https://www.chltech.net/manage/includes/api.php' api_username = 'XMBoFf3A3RvUCQnsJaQEHjQefx9W5FWC' api_password = '4yCdTGPvQWS2tnRFYS6CgIG7HMcmtLWZ' api_action = 'validatelogin' api_params = { 'username': api_username, 'password': api_password, 'action': api_action, 'responsetype': 'json', 'email': email, 'password2': password, } response = requests.post(api_url, data=api_params) if response.status_code == 200: data = response.json() if data['result'] == 'success': user_first_name = data.get('firstname', '') user_last_name = data.get('lastname', '') request.session['user_first_name'] = user_first_name # request.session['user_last_name'] = user_last_name print(user_first_name,user_last_name) messages.success(request , "login successful") return redirect('whmcs') else: messages.error(request, "Invalid email or password.") else: messages.error(request, f"Login failed: HTTP Error {response.status_code}") form = CustomAuthenticationForm() return render(request, 'login.html', {'form': form}) def whmcs(request): user_first_name = request.session.get('user_first_name', '') user_last_name = request.session.get('user_last_name', '') return render(request, 'whmcs.html', {'user_first_name': user_first_name, 'user_last_name': user_last_name})` ) whmcs.html ( <!DOCTYPE html> <html> <head> <title>Client Emails</title> </head> <body> {% block content %} <h1>Welcome, {{ user_first_name }} {{ user_last_name }}</h1> {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <div class="alter alter-danger"> {{message}} </div> {% else %} <div class="alert … -
django-livereload-server installation
I am new to django and trying to install django-livereload-server In the installation guide, somewhere says: You need to inject the loading of the livereload javascript. You can do this in one of two ways: Through middleware by adding 'livereload.middleware.LiveReloadScript' to MIDDLEWARE_CLASSES (probably at the end): MIDDLEWARE_CLASSES = ( ... 'livereload.middleware.LiveReloadScript', ) Through a templatetag in your base.html (or similar) template: {% load livereload_tags %} ... {% livereload_script %} For the first solution, I've noticed there is no MIDDLEWARE_CLASSE = () in the settings.py file (django 4.2.4). Theres only a MIDDLEWARE_CLASSE = [] list, and putting 'livereload.middleware.LiveReloadScript' in it does not work. (Live reload runs, but can't refresh the page.) Where should I put 'livereload.middleware.LiveReloadScript' to get it to work? Whats the instruction for the second solution? I don't see the base.html in my project/ app. Should I create it myself? Appreciate any help! Using: VSCode, django, enve, Installed packages: asgiref 3.7.2 beautifulsoup4 4.12.2 Django 4.2.4 django-livereload-server 0.4 dnspython 2.4.2 et-xmlfile 1.1.0 greenlet 2.0.2 pip 23.2.1 setuptools 63.2.0 six 1.16.0 soupsieve 2.4.1 sqlparse 0.4.4 tornado 6.3.3 typing_extensions 4.7.1 tzdata 2023.3 -
How to check if field in a table object is equal to specific string in django template language?
model name=ApplicationForm test_selection is one of the charfiled in ApplicationForm(table) views.py applied_student=get_object_or_404(ApplicationForm, dob=dob,id=app_id) i am using this query in view and sending this data to my template... I want to check if applied_student.test_selection=="selected" but its not working i tried using {% if student.test_selection =="selected" %} If worked {% endif %} i want to compare this filed with stored string value in table in djanog template -
Customizing JWT token claims in Django
I'm trying to customize my JWT token and what ever I do I got an error like this : ImportError: cannot import name 'MyTokenObtainPairView' from 'base.api.serializers' (D:\Anaraki\api\bakend\base\api\serializers.py) here is my serializers.py file: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer my urls.py file: from django.urls import path from . import views from rest_framework_simplejwt.views import (TokenRefreshView, TokenObtainPairView) from .serializers import MyTokenObtainPairView # to customize the token we use this one insted . urlpatterns = [ path('',views.getRoutes), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] I did everything's that doc said but I still got this ... error, please help me. -
In Django, which has faster and better performance beween ".filter(a).filter(b)" and "Q objects" and "or/and queries" and "keyword queries"
Simply put, what is the order of performance and speed among the following similar looking queries in the Django ORM? .filter(a).filter(b) instances = Model.objects.filter(a=A).filter(b=B) Q objects instances = Model.objects.filter(Q(a=A) & Q(b=B)) or/and queries instances = Model.objects.filter(a=A) & Model.objects.filter(b=B) keyword queries instnaces = Model.objects.filter(a=A, b=B) Thank you, and please leave any comments below. AND please don't copy and paste chatgpt or any other ai services.