Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Location of signals in Django
I am confused about the use of signals. Where should I put the signal codes so that they are orderly and appropriate? I have a signal file for an app. Where do I call it? -
Is it possible to store a queue-like structure in Django database?
This might be a stupid question, but I'm new to databases and I could't find an answer anywhere. Is it possible to somehow store a FIFO queue in django? Some equivalent of python's collections.deque? Let's say I hypothetically have a model AverageRate, which stores a queue of up to 24 numbers and an average value of those numbers: (sum(numbers) / len (numbers)). class AverageRate: last_24_numbers = # FIFO queue up to 24 elements long average_value = # average value of last_24_numbers Every hour a function adds a new number to last_24_numbers and calculates average value. If the queue reaches 24 elements, then to append a new element to the end of the queue, it must pop the oldest element from the beginning of the queue. Honestly the only solution I came up with was to possibly convert the queue to string and store it in CharField, and then convert it back every time I need to use it. But I dunno... it just feels like not the best idea. I would obviously want to use the most efficient solution. -
How do I unfreeze or solve my python libraries being frozen problem
enter image description hereenter image description here I'm trying to make a test project and downloaded bootstrap in different ways but then this happened can anyone help me solve this. I tried deleting and downloading python again but that didnt work. -
How to create django model for tenants and properties?
2.2.Property Listing Module Property Details: Create property profile with information like Property name and address, location, features. Each property will have multiple units. Each unit will have features like rent cost,Type- 1BHK,2BHK,3BHK,4BHK property profile view with units and assigned tenant information 2.3.Tenant Management Module Create a tenant profile with name, address, document proofs. Assign a tenant with a unit under a property with details like agreement end date, monthly rent date. Need a search based on features added for units and properties. Show tenant profile view with personal information and rental information from django.db import models class Property(models.Model): name = models.CharField(max_length=100) address = models.TextField() location = models.CharField(max_length=100) features = models.TextField() def __str__(self): return self.name class Meta: verbose_name_plural = "properties" class Unit(models.Model): UNIT_TYPES = [ ('1BHK', '1BHK'), ('2BHK', '2BHK'), ('3BHK', '3BHK'), ('4BHK', '4BHK'), ] rent_cost = models.IntegerField() unit_type = models.CharField(max_length=4, choices=UNIT_TYPES) property = models.ForeignKey(Property, on_delete=models.CASCADE, related_name='units') def __str__(self): return f"{self.unit_type} unit in {self.property.name}" class Tenant(models.Model): name= models.CharField() address=models.TextField() document_proofs=models.ImageField() assigned_unit = models.ForeignKey(Unit, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self) -> str: return self.name This what I developed.Is this correct way of creating model. how to include agreement end date, monthly rent date in this model -
django AdminEmailHandler send sensitive information when include_html is False
i use django.utils.log.AdminEmailHandler for my logging hander class. in django docs, title was said as a security note to turn False include_html for not sending sensitive information. this is my Logging Config: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters':{ 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, }, 'handlers': { 'django_mail_logger': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', 'include_html': False, }, }, 'loggers': { 'django': { 'handlers': ['django_mail_logger'], 'level': 'INFO', }, }, } as the note was mentioned in docs , i turn False the include_html to not send tranceback and etc but when error occurs my django app send traceback, settings and etc as when debug is false and only doesn't use HTML. is django docs correct or i misconfigure handler? i use django 4.2 and python 3.8. i try the logging configure which i mentioned and i expect email me less information but i receive sensitive informations. -
Why does django only allows access to the widget attributes when it renders a field into a form
I have a question about Django template rendering. Right now I use it to build a full-stack app, so the issue is that when I try to override a default form rendering behavior, I see that despite I can possibly overwrite default html without boilerplate, it is becoming harder as I dive deeper. Let's take a look on the excerpt from table.html which renders form as table. ... {{ field }} {% if field.help_text %} <br> <span class="helptext"{% if field.auto_id %} id="{{ field.auto_id }}_helptext"{% endif %}>{{ field.help_text|safe }}</span> ... Here we see that every form Field will render like <label> ~<input> <span> (help_text) But what if we want to overwrite default Field(e.g. ImageField) rendering behaviour to produce html portion like the below code to be able to add a preview avatar before the <input>-<help text> combination. <div> <img>(preview) <div> <input> <span>{{ field.help_text|safe }}</span> </div> </div> We can't just write custom html for our field, like django/forms/widgets/text.html, because it only has Widget in the context. So without boilerplate it is straightforward to overwrite how <input> tag is rendered using custom html files, but it is not straightforward how to make custom <label> and help_text rendering on per-field-class basis. Seems like we … -
Does Django CMS Support ASGI?
It seems like it should, given it supports Django 3, but I can't find any information about this at all. Searching the Django docs, the Django CMS docs, Google, here. Nothing relating to django cms specifically and asgi are returned. -
Django item swap
Please i need help implementing a feature in django where User A can request an item from User B and User B can choose to decline the request or choose to swap with one of User A items. class item_request(models.model): requester = models.foreignkey(User, on_delete=models.CASCADE) owner = models.foreignkey(User, on_delete=models.CASCADE) item = models.Foreignkey(Item, on_delete=models.CASCADE) status = models.CharField(max_length=30, default="pending") -
How DO I BLOCK URLS in django?
How to block urls in django? What I mean is if I have a website www.example.comand I want users to sign in before entering www.example.com/price and restrict users who will try to edit the URL in browser and enter? -
Hi, I am trying to create models in Django using Visual Studio. I am running the code in interactive and get errors
Here are the details - >>> from rntax6 import settings >>> # settings.configure(DEBUG=False) ... ... from asyncio.windows_events import NULL ... >>> from logging import NullHandler >>> from django.db import models >>> from django.db.models import Model >>> class Services(models.Model): ... service = models.CharField(max_length=255) ... class Meta: ... app_label = 'rntxapp6' ... Traceback (most recent call last): File "", line 1, in File "C:\Users\rabin03\source\pysrc\pyproj311\rntax6\env-rntx6\Lib\site-packages\django\db\models\base.py", line 129, in new app_config = apps.get_containing_app_config(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rabin03\source\pysrc\pyproj311\rntax6\env-rntx6\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "C:\Users\rabin03\source\pysrc\pyproj311\rntax6\env-rntx6\Lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\rabin03\source\pysrc\pyproj311\rntax6\env-rntx6\Lib\site-packages\django\conf_init_.py", line 91, in getattr val = getattr(wrapped, name) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rabin03\source\pysrc\pyproj311\rntax6\env-rntx6\Lib\site-packages\django\conf_init.py", line 293, in getattr return getattr(self.default_settings, name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'str' object has no attribute 'INSTALLED_APPS' def str(self): ... return self.name ... The last part floors me. Any help would be very much appreciated. I have tried changing the Settings a number of different ways but get even more errors. -
I got athentication error when im trying to post a request using axios api in vue.js
commerce website and this is my checkout.vue code when post request an authenticated error 401 and i don't know where the problem is some says its becuase axios and i should replace it with fetch api,any suggestion? const data={ 'first_name':this.first_name, 'last_name':this.last_name, 'eamil':this.eamil, 'address':this.address, "zipcode":this.zipcode, "place":this.place, "phone":this.phone, "items":items, 'stripe_token':token.id } await axios .post("/api/v1/checkout/",data) .then(response=>{ this.$store.commit("clearCart") this.$router.push("/cart/success") }) .catch(error=>{ this.errors.push("Something went wrong. Please try again") console.log(error) }) this.$store.commit('setIsLoading',false) } -
CSRF Failed: CSRF token missing django REST + Vuejs obtain_auth_token
I am making POST request to get the token from the backend. I have traefik to provide https for security reason. It works. But when I deploy Vuejs and make POST with the same payload. I got the error in the Chrome browser. detail: "CSRF Failed: CSRF token missing." I have search over the stackoverflow. I would like to follow the security concept then disable CSRF is not an option. import {ref} from "vue"; import {BACKEND_URL} from "../constants"; const getLoginToken = () => { const token = ref('') const tokenError = ref(null) const fetchToken = async(username, password) => { try{ const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ "username": username, "password": password }), redirect: 'follow', } const url = BACKEND_URL + '/api/auth-token/' console.log(url) let data = await fetch(url, requestOptions) if(!data.ok){ throw Error(data.statusText) } token.value = await data.json() } catch(err){ tokenError.value = err.message console.log(tokenError.value) } } return { token, tokenError, fetchToken } } export default getLoginToken settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10, "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ), 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", } `urls.py from django.views.decorators.csrf import csrf_exempt ... path("api/auth-token/", csrf_exempt(obtain_auth_token)), ... But does not work. Problem: I am unable to … -
Friendly duration picker ready to be used as a form widget in a Django application
I need to let a user select a duration in a form field of a Django application. I'm already using bootstrap (namely django-bootstrap-datepicker-plus) to select other fields such as Date, Time and DateTime. But duration is something lightly different. I'm currently having a simple integer field where the user is asked to input the duration value in minutes. But once the duration last for some hours, e.g. 07h24, the user has to compute to how many minutes it corresponds before entering the right value. This is error prone. On the opposite, if I ask the user to input values in hours, 7h20 would become 7.3333. This is also error prone and it's not precise in that case. That's why I'm searching for a true duration picker. Using two DateTime pickers and computing the timedelta is also not an option for the lack of user-friendliness. Hence my question: does a friendly duration picker exists inside bootstrap for Django and if not, does something other exist? I guess I don't have to reinvent the wheel, but I wasn't able to figure out something which integrates well with Django 4. Ideally, jQuery should also be avoided. My current research led me to these … -
How to setup email verification with Django-Verify-Email
I get an invalid link in the email every time i register a new user with this package here is my code def signup(request, form_class, template_name, success_message, redirect_url): if request.user.is_authenticated: return redirect(redirect_url) form = form_class() if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): send_verification_email(request, form) form.save() messages.success(request, success_message) return redirect(redirect_url) else: messages.error( request, f'Error creating account. Please check the form.') return render(request, template_name, {'form': form}) context = {'form': form} return render(request, template_name, context) def student_signup(request): return signup( request, StudentRegistrationForm, 'user/student/signup.html', 'Student account created successfully.', 'user:signin' ) Am i just using the standard setting. Am i missing anything? -
Error 508 Invalid data in MERCHANT_ID field. Please contact the merchant
Can anyone help me understand why do I get this error? I used the merchant_id that I was given at https://developer.globalpay.com/ <<script> $(document).ready(function() { $.getJSON("sdkRequestEndpoint", function(jsonFromRequestEndpoint) { RealexHpp.setHppUrl("https://pay.sandbox.realexpayments.com/pay"); RealexHpp.lightbox.init("payButtonId", "responseEndpoint", jsonFromRequestEndpoint); }); }); </script> <!DOCTYPE html> <html lang="en"> <head> <!-- Add these links in the head section of your HTML file --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> </head> <body> <center> <h2>Make a Booking</h2> <form action="https://pay.sandbox.realexpayments.com/pay" method="POST" target="iframe"> <input type="hidden" name="TIMESTAMP" value="20180613110737"> <input type="hidden" name="MERCHANT_ID" value="MER_7e3e2c7df34f42819b3edee31022ee3f"> //my Merchant_ID <input type="hidden" name="ACCOUNT" value="internet"> <input type="hidden" name="ORDER_ID" value="N6qsk4kYRZihmPrTXWYS6g"> <input type="hidden" name="AMOUNT" value="1999"> <input type="hidden" name="CURRENCY" value="EUR"> <input type="hidden" name="AUTO_SETTLE_FLAG" value="1"> <input type="hidden" name="COMMENT1" value="Mobile Channel"> <input type="hidden" name="HPP_VERSION" value="2"> <input type="hidden" name="HPP_CHANNEL" value="ECOM"> <input type="hidden" name="HPP_LANG" value="en"> <!-- Begin 3D Secure 2 Mandatory and Recommended Fields --> <input type="hidden" name="HPP_CUSTOMER_EMAIL" value="test@example.com"> <input type="hidden" name="HPP_CUSTOMER_PHONENUMBER_MOBILE" value="44|789456123"> <input type="hidden" name="HPP_BILLING_STREET1" value="Flat 123"> <input type="hidden" name="HPP_BILLING_STREET2" value="House 456"> <input type="hidden" name="HPP_BILLING_STREET3" value="Unit 4"> <input type="hidden" name="HPP_BILLING_CITY" value="Halifax"> <input type="hidden" name="HPP_BILLING_POSTALCODE" value="W5 9HR"> <input type="hidden" name="HPP_BILLING_COUNTRY" value="826"> <input type="hidden" name="HPP_SHIPPING_STREET1" value="Apartment 852"> <input type="hidden" name="HPP_SHIPPING_STREET2" value="Complex 741"> <input type="hidden" name="HPP_SHIPPING_STREET3" value="House 963"> <input type="hidden" name="HPP_SHIPPING_CITY" value="Chicago"> <input type="hidden" name="HPP_SHIPPING_STATE" value="IL"> <input type="hidden" name="HPP_SHIPPING_POSTALCODE" value="50001"> <input type="hidden" name="HPP_SHIPPING_COUNTRY" value="840"> <input type="hidden" name="HPP_ADDRESS_MATCH_INDICATOR" value="FALSE"> <input type="hidden" name="HPP_CHALLENGE_REQUEST_INDICATOR" value="NO_PREFERENCE"> <!-- … -
Custom user model vs. additional model
Due to lack of knowledge, when faced with the need to store additional information about users, I created additional UserInfo model and referenced it by foreign key to the standard User model. I have since learned two things: It is recommended to have a custom user model. It is tricky to switch mid-project (this being the best way so far as far as I understand). I would like to understand: If the fields in UserInfo are not used for authentication, is there any reason to merge those into the user model? What do I stand to gain by taking the time to abandon my current approach and switch to a custom user model? -
React and Django deployment blank page and 404 errors on static files with cpanel
I wanted to deploy my django and react application on my domain name via my host I have setup my python because when we go to the url dimitridenis.com/admin we arrive at my django admin portal, I implemented React and did the npm install then the build in my cpanel terminal, however I found myself with a white screen and 404 errors on static files, I tried several times to change my build, the paths in my settings.py file but I still don't understand White screen with errors If you have any ideas to give me, I'm interested -
Can we use django-distill to host a Django website in Github pages?
I'm exploring options for hosting a Django website on GitHub Pages, and I came across the django-distill package. I'm wondering if it's feasible to use django-distill for hosting a Django website on GitHub Pages. Here are some specific points I'm curious about: *Has anyone successfully used django-distill to deploy a Django website on GitHub Pages? *Are there any specific configurations or steps that need to be taken to make it work with GitHub Pages? I appreciate any insights or experiences you can share regarding using django-distill or any other approach for deploying a Django site on GitHub Pages. I attempted to use django-distill to deploy a Django website on GitHub Pages. My approach involved configuring django-distill and following the standard steps for deploying a Django project. However, despite my efforts, I encountered challenges, and the deployment did not work as expected. Link: https://django-distill.com/ -
Uncaught TypeError: Cannot read properties of null (reading 'defaultPrevented')
seem to be getting a script error that mentions both bootstrap alert and my own close alert tag. I have a script that closes alerts after 2.5s when a script is created. It is tied to user actions, for example if a user creates a blog post or deletes a comment, an alert shows with the User task and then auto closes the tag. i seem to be getting a Uncaught TypeError in console and cant figure out why, i can only speculate that its because its looking for a alerts msg that isnt there yet? script.js // // Event listener for auto close message function using DOM Content Loaded // // Javascript function for auto close messages // document.addEventListener("DOMContentLoaded", alertTimeout); document.addEventListener("DOMContentLoaded", (alertTimeoutalertTimeout) => { setTimeout(function () { let messages = document.getElementById("msg"); let alert = new bootstrap.Alert(messages); alert.close(); }, 2500); }); index.html bootstrap script <!-- Bootstrap Scripts --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </html> Console Error code Uncaught TypeError: Cannot read properties of null (reading 'defaultPrevented') at Q.close (alert.js:38:60) at script.js:11:11 close @ alert.js:38 (anonymous) @ script.js:11 setTimeout (async) (anonymous) @ script.js:7 I have tried to add a document ready to the script and have tried different … -
django get all the likes made for a post
i am trying to get all the likes for a specific in the home templates and also they are many products in the template. this is my views.py @login_required def home(request): products = Product.objects.all() like_counts = {product.id: Like.objects.filter(product=product).count() for product in products} liked_products = Like.objects.filter(user=request.user, product__in=products).values_list('product', flat=True) context = { "products": products, "liked_products": liked_products, "like_counts": like_counts, "categories": Category.objects.all(), } return render(request, 'shop/index.html', context) @login_required def likeProduct(request, product_id): product = get_object_or_404(Product, id=product_id) # Check if the user has already liked the product if not Like.objects.filter(user=request.user, product=product).exists(): # Create a new Like object Like.objects.create(user=request.user, product=product) print('product liked') likes = Like.objects.all().count return JsonResponse({"status": "success","likes":f'{likes}'}) else: liked = Like.objects.get(user=request.user) liked.delete() print('product like removed') likes = Like.objects.all().count return JsonResponse({"status": "success","likes":f'{likes}'}) def views_count(request,product_id):` item = Product.objects.get(id=product_id) item.views_count += 1 item.save() return redirect('home') this is my index.html and i am got stuck here now the django is giving all sorts of weird errors and do not know how to solve it: {% csrf_token %} <div class="d-flex justify-content-between"> <button onclick="likeProduct({{ product.id }})" class="btn shadow-none bg-transparent rounded-pill"> <i class="{% if product.id in liked_products %}fas{% else %}far{% endif %} fa-heart"></i> {{ like_counts|default:"0"|get:product.id }} </button> <button class="btn shadow-none bg-transparent rounded-pill"><i class="fas fa-star"></i></button> <button class="btn btn-outline-primary"><i class="fas fa-comment"></i></button> </div> -
Problem connecting a django project with a mysql database in a docker container
I can't access the db from tableplus, mysqlworkbench or django, but I can access it from the docker container console. when i try to connect with docker exec -it 2ac7cefb3198 /bin/bas mysql -proot -uroot i can access Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 9 Server version: 8.2.0 MySQL Community Server - GPL Copyright (c) 2000, 2023, Oracle and/or its affiliates. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> show databases; +--------------------+ | Database | +--------------------+ | hbrs_bd | | information_schema | | mysql | | performance_schema | | sys | +--------------------+ 5 rows in set (0.01 sec) but when i try with django 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'hbrs_bd', 'HOST': 'localhost', 'USER': 'root', 'PORT':'3308', 'PASSWORD': 'root' } }``` i had this response (1045, "Access denied for user 'root'@'localhost' (using password: YES)") this is my dockerfile FROM mysql:8 ENV MYSQL_ROOT_PASSWORD root COPY ./hbrs_bd.sql /docker-entrypoint-initdb.d/hbrs_bd.sql and this is my docker compose file services: database: build: . ports: - "3308:3308" some body had some expierencie with … -
What framework should I learn for backend [closed]
What framework should I learn for backend in 2024? I have tried Django and Laravel I just do not know witch one is better to get a job these times and I am going with react too so I see a lot of people use node js but I just know it is no good in my country to learn int. that is why I am going with these two frameworks ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, do not read the next lines : it is just nothing so that stack overflow tkae my qustion it said 220 but i just do nt know why it still do not want to send this qustion to you all man come onnnnnnnnnnnnnnnnnnnn it is my first time on this website and I am thinking of going back to chat gpt 3 not even 4 if u do not allow this man come on -
ModuleNotFoundError: No module named '_sqlite3' trying to connect with sqlalchmey and pandas
I am using Python version 3.10. I'm attempting to connect a MySQL database to SQLalchemy and Pandas. The local environment is working fine. But when I deployed in Ubuntu, I got ModuleNotFoundError: No module named '_sqlite3'. Note:- But I tried to connect with Django Orm with Ubuntu, which was also working as expected. the only problem with sqlalchemy and Pandas. from sqlalchemy import create_engine import pandas as pd engine = create_engine(url,echo=False) ## en conn = engine.connect() df = pd.read_sql_query('SELECT * FROM role_master', con=engine) Need solution to fix this issue. -
How to convert a synchronous view to async view in Django
I'm working on a django view to get list of available riders. I first created in a synchronous context and when I tested it, it worked as expected. I need it to be in an asynchronous context, but when I tried to convert i to an async context, I get this error message below: raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Here's the code in an async context I came up with trying to convert to an async context, but got the error above: riderexpert_db = firestore.AsyncClient(project="riderexpert", database="riderexpert-db") class GetAvailableRidersView(APIView): permission_classes = [IsAuthenticated] SEARCH_RADIUS_METERS = 10 async def get_google_maps_client(self): """Initialize and return the asynchronous Google Maps API client.""" return GoogleMapsClient(key=settings.GOOGLE_MAPS_API_KEY) async def validate_parameters(self, order_location, item_capacity, is_fragile): """Validate input parameters.""" try: item_capacity = float(item_capacity) is_fragile = str_to_bool(is_fragile) except (ValueError, TypeError): return False, "Invalid or missing parameters" if not all( [ order_location is not None and isinstance(order_location, str), item_capacity is not None and isinstance(item_capacity, (int, float)), is_fragile is not None and isinstance(is_fragile, bool), ] ): return False, "Invalid or missing parameters" return True, "" def handle_google_maps_api_error(self, e): """Handle Google Maps API errors.""" return Response( {"status": "error", "message": f"Google Maps API error: {str(e)}"}, … -
Token is automatically changing on every request
I get access and refresh token after logging in by following code. class Employee_Login(APIView): permission_classes=[AllowAny] employee_login_data = serializers.employee_login_serializer def post(self,request): try: employee_data = self.employee_login_data(data=request.data) employee_data.is_valid(raise_exception=True) data = employee_data.validated_data employee = authenticate(request,email=data.get('email'), password= data.get('password')) if not employee: return Http404("Employee not found") if not employee.is_verified: raise ForbiddenException("Employee is not verified") payloads = { "user": "admin" if employee.is_admin and employee.is_verified and employee.is_staff else "staff" if employee.is_staff and employee.is_verified else "" } employee_detail = { "name":employee.name, "email":employee.email, "type":"admin" if employee.is_admin and employee.is_staff and employee.is_verified else "staff" if employee.is_admin and employee.is_verified else "" } refresh = RefreshToken.for_user(employee) refresh.payload.update(payloads) acess_token = str(refresh.access_token) refresh_token = str(refresh) return Response({"success":True, "data":employee_detail, "token":{"access":acess_token,"refresh":refresh_token}}) except Exception as e: return Response({"success":False,"message":str(e)}) The problem is, when I use the access token obtained from above code in below custom permission class class AdminPermission(permissions.BasePermission): def has_permission(self, request, view): print("Here",AccessToken(request.auth).payload) STAFF_METHODS = ['GET','POST','PATCH'] USER_METHODS = ['GET'] if request.method in USER_METHODS: return True print(AccessToken(request.auth)) if request.user.is_authenticated: if request.user.is_admin and request.user.is_staff and request.user.is_verified: return True if not request.user.is_admin and request.user.is_staff and request.user.is_verified and request.method in STAFF_METHODS: return True return False The print(AccessToken(request.auth)) is printing different token than the token that I passed from request. And it is printing different things in every request. I am frustrated by this …