Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overriding create() for class based generic views
How can I perform some logic prior to saving a record within my generic view? I believe the actual saving logic occurs within super().create(). class WalletListCreateAPIView(generics.ListCreateAPIView): queryset = Wallet.objects.all() serializer_class = WalletSerializer def create(self, request, *args, **kwargs): # Some logic here prior to saving return super().create(request, *args, **kwargs) For instance, I would like to create the value for balance instead of relying on the value from the request class Wallet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=34) balance = models.DecimalField(default=0, max_digits=16, decimal_places=8) slug = models.SlugField(max_length=34, blank=True, null=True) -
RASA 3.2.0 Server Coonection with Django Server
I want to connect Rasa 3.2.0 with Django for a Frontend Webchat. I have gone through this link: - https://www.youtube.com/watch?v=XMAw_bKTLbA and this link: - https://forum.rasa.com/t/rasa-chatbot-blank-page/55721/6. But somehow it is not connecting and showing Blank White Page. Here is the Template HTML File: - {% load static %} <link rel="stylesheet" href="{% static 'Chatroom.css' %}"/> <div class="chat-container"></div> <script src="{% static 'Chatroom.js' %}"></script> <script type="text/javascript"> var chatroom = new window.Chatroom({ host: "http://localhost:5005/webhook", title: "Rasa Assistant", container: document.querySelector(".chat-container"), welcomeMessage: "Hi, I am AIChatbot!", speechRecognition: "en-US", voiceLang: "en-US" }); chatroom.openChat(); </script> I also tried changing the Chatroom.js and .css file which was coming from AWS S3 Bucket...still get same problem. -
How do you connect an amazon rds to a django app
I have added the correct name, engine, user, password etc. Then I modified the inbound security rules to give my computer access to the database and I still cant connect the postgres database to the django app does anyone know what could cause this? I keep getting this error port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? -
OperationalError at / no such column: accounts_customer.user_id
i have been following this tutorial I was going smoothly but i got an error .i am not sure how to resolve it .I added onetoone relationship to the customer with user model.And now got this user. `models.py enter code here from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import User class customer(models.Model): user=models.OneToOneField(User,null=True,on_delete=models.CASCADE) id=models.UUIDField(primary_key=True,default=uuid.uuid4) name=models.CharField(max_length=200,null=True) phone_no=models.CharField(max_length=200, validators [RegexValidator(r'^\d{1,10}$')],null=True) email=models.EmailField(max_length=200,null=True) def __str__(self): return self.name class tag(models.Model): name=models.CharField(max_length=200,null=True) def __str__(self): return self.name class products(models.Model): categories=[ ('indoor','indoor'), ('outdoor','outdoor') ] name=models.CharField(max_length=200,null=True) price=models.FloatField(null=True) manufacturedate=models.DateTimeField(auto_now_add=True,null=True) description:models.TextField(null=True) categories=models.CharField(max_length=200,null=True,choices=categories) tag=models.ManyToManyField(tag) def __str__(self): return self.name class order(models.Model): status=[ ('pending','pending'), ('out of stock','out of stock',), ('Delivered',('Delivered')) ] ordered_date=models.DateTimeField(auto_now_add=True) status=models.CharField(max_length=200,null=True,choices=status) customer=models.ForeignKey(customer,null=True,on_delete=models.SET_NULL) product=models.ForeignKey(products,null=True,on_delete=models.SET_NULL) def __str__(self): return self.product.name I am really confused . I am stuck here for a while.It was all fineuntil i added onetoone relationship. views.py enter code here from multiprocessing import context from django.shortcuts import render,redirect from django.contrib.auth.models import Group from .models import * from .forms import CreateCustomer,CreateOrder,CreateUser from .filters import FilterSearch from django.contrib.auth import logout,login,authenticate from django.contrib import messages from django.contrib.auth.decorators import login_required from .decorators import allowed_users,admin_only def registeruser(request): if request.user.is_authenticated: return redirect('home') else : form=CreateUser() if request.method=='POST': form=CreateUser(request.POST) if form.is_valid(): user=form.save() group=Group.objects.get(name='customer') user.groups.add(group) login(request,user) return redirect('home') context={'form':form} return render(request,'accounts/registeruser.html',context) def loginuser(request): if request.user.is_authenticated: return redirect('home') … -
How to get a django instance to have one to many users relation
I have a company table as follows: class Company(models.Model): users = models.ManyToManyField(settings.AUTH_USER_MODEL, default=None) My plan is that a given company instance can have more than one user account tied to it. But from above, when a company is created, the users field is ending up with all the users in the users table. That is not I want. I want that users are manually added rather than just populating the field with all users in the database: How can I set this up so that a given company instance can only have the users added to it rather than all database users? -
What is the best way to make logs with React and Python(Django)?
If I have a frontend with React and a backend with Python Django, how can I integrate custom logs? If I need to store which functions were pressed and when? Example: We have a PostgreSQL database and there is a file called Logs.txt. When the user opens a specific route, we need to save the time and route name in this file. Also, if there are some buttons that run some functions, we also need to save the time and function name in this log file. Do I need to every time to make a simple request to the backend to save new data about users' pressed history? Or is there some better approach? -
Django doesn't process POST request's payload from axios
I have React + Django REST Framework stack. DRF works as API and React as SPA. And I'm really confused why POST request doesn't work. If any additional information is required, please, ask me. In React I'm making POST request with axios like following: axios .post( '/api/auth/register/', registrationInfo, { headers: { "Content-Type": "application/json" } } ) .then((response) => { setRegistrationStatus(response.data.status) }) .catch((error) => { console.log(error) }) The frontend part of request seems to work fine. Payload and headers are shown: , In DRF My serializer for registration look like this: class RegistrationSerializer(UserSerializer): password = serializers.CharField(max_length=200, write_only=True, required=True) email = serializers.EmailField(required=True, write_only=True, max_length=200) class Meta: model = CustomUser fields = ['id', 'email', 'password', 'phone', 'first_name', 'last_name', 'is_active', 'created_at', 'modified_at'] def create(self, validated_data): try: user = CustomUser.objects.get(email=validated_data['email']) except ObjectDoesNotExist: user = CustomUser.objects.create_user(**validated_data) return user ...and views: class RegistrationViewSet(viewsets.ModelViewSet, TokenObtainPairView): serializer_class = RegistrationSerializer permission_classes = (AllowAny,) http_method_names = ['post'] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=self.request.query_params) serializer.is_valid(raise_exception=True) user = serializer.save() refresh = RefreshToken.for_user(user) res = { "refresh": str(refresh), "access": str(refresh.access_token), } return Response({ "user": serializer.data, "refresh": res["refresh"], "token": res["access"] }, status=status.HTTP_201_CREATED) The output of DRF when making request is confusing. In developer tools-network the response is {"email":["This field is required."],"password":["This field is … -
Celery Beat sending all periodic tasks as due on restart even if they have just run
I am running a celery worker and celery beat with DatabaseScheduler. I am running these on Heroku along with a django web application. They are being used to send emails and texts at regular intervals, Once per day at midnight for emails and 730am for texts. I have defined the tasks manually using a chrontab in Periodic Tasks table, but I have also tried defining them in the codebase using celeryapp.conf.beat_schedule, both behave the same. The tasks look like this periodic tasks in django admin The issue I am having is that Heroku restarts its dynos once per day as a policy, and when this happens, the celery beat dyno runs my periodic tasks for some reason. The debug log reads "Scheduler: Sending due task" as if it is normal, whether they are due then or not. I do not know why this is happening. I have celery results running as well with postgres backed task results and that looks like this, where I have the tasks running at the correct times (midnight and 730am), but also at some random time when heroku restarts the dynos. How can I stop the tasks from running when this restart happens? Why are … -
Django Queryset return all if field is empty when there is OneToMany relationship
I have an html page in which one can search for a car based on several criteria. How do I tell django orm to return all if a field is empty? I checked this question and implemented the same idea of the first answer but it doesn't work for the foreign fields especially the model field, which if left empty, I get this error. Here are my classes class City(models.Model): name = models.CharField(max_length=10, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) class PowerSource(models.Model): source = models.CharField(max_length=8) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Manufacturer(models.Model): manufacturer = models.CharField(max_length=45) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class CarModel(models.Model): model = models.CharField(max_length=45) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) manufacturer = models.ForeignKey(Manufacturer, related_name='car_models', on_delete=models.CASCADE) class Car(models.Model): color = models.CharField(max_length=10, null=True) year = models.IntegerField(null=True, validators=[MinValueValidator(datetime.today().year-120), MaxValueValidator(datetime.today().year+1)]) num_passengers = models.IntegerField(validators=[MinValueValidator(1)], null=True) transmission = models.CharField(max_length=9, null=True) status = models.CharField(max_length=4, null=True) price = models.IntegerField(validators=[MinValueValidator(1)], null=True) bhp = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) city = models.ForeignKey(City, related_name='cars', on_delete=models.CASCADE) power_source = models.ForeignKey(PowerSource, related_name='cars', on_delete=models.CASCADE) model = models.ForeignKey(CarModel, related_name='cars', on_delete=models.CASCADE) For example, if I choose a manufacturer and leave other fields empy I should get all cars from that manufacturer regardless of color, year, etc. However, I … -
Multistepform with multiple images Django
Hi I am doing a multistepform in django that can add multiple image data (description and image). All my mutistepform is okay and adding to the database if it does not have add another entry button like my media. I would like to add multiple media files in the database. How can I achieve it? Below are my snippets of the codes. Models class IncidentMedia(models.Model): incident_general = models.OneToOneField(IncidentGeneral, on_delete=models.CASCADE) media_description = models.TextField(max_length=250, blank=True) incident_upload_photovideo = models.ImageField(default='user.jpeg', upload_to='incident_report/image') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.id Views def multistepformexample(request): # if request.method!="POST": # return redirect ('user_reports') profile = get_object_or_404(UserProfile, user=request.user) if request.method == 'POST': form = UserReportForm(request.POST or None, request.FILES or None) form_general = IncidentGeneralForm(request.POST or None, request.FILES or None) # form_people = IncidentRemarksForm(request.POST or None, request.FILES or None) form_media = IncidentRemarksForm(request.POST or None, request.FILES or None) form_remarks = IncidentRemarksForm(request.POST or None, request.FILES or None) try: if form.is_valid() and form_general.is_valid() and form_remarks.is_valid(): date=request.POST.get("date") time=request.POST.get("time") address=request.POST.get("address") city=request.POST.get("city") pin_code=request.POST.get("pin_code") latitude=request.POST.get("latitude") longitude=request.POST.get("longitude") description=request.POST.get("description") # accident_factor = AccidentCausation.objects.get(pk=request.id) # accident_subcategory = AccidentCausationSub.objects.get(pk=request.id) # collision_type = CollisionType.objects.get(pk=request.id) # collision_subcategory = CollisionTypeSub.objects.get(pk=request.id) # crash_type = CrashType.objects.get(pk=request.id) accident_factor1 = request.POST.get("accident_factor") accident_factor = AccidentCausation.objects.get(pk=accident_factor1) # accident_subcategory1 = request.POST.get("accident_subcategory") # accident_subcategory = AccidentCausationSub.objects.get(pk=accident_subcategory1) collision_type1 = request.POST.get("collision_type") collision_type = … -
Custom django CharField returns a Path instance
I have a model that tracks details of files (but does not serve the file itself). Currently, I am using a CharField to store the path, but it gets cumbersome to constantly convert that field to a Path instance. Model looks like this: class MyFile(models.Model): path = models.CharField(max_length=100) checksum = models.CharField(max_length=32) content_last_updated = models.DateTimeField(null=True) @property def is_image(self) -> bool: return Path(self.path).suffix == '.jpg' I tried to define a custom Field by subclassing CharField class PathnameField(models.CharField): def from_db_value(self, value, expression, connection): return Path(value) if value is not None else value If I substitute this field class in the model, nothing breaks but the field type is still a str. afile = MyFile.objects.create(path=Path('foo/bar.txt'), checksum='000') afile.refresh_from_db() assert isinstance(afile.path, Path) Has anyone tried this? -
save logs of database changes into database in django
I need to save log for changes of some tables into database so admin can read the logs and track users activities for example, I need to save logs of user table changes with these infos datetime chage happend, user who changed the user info (can be user him/her self or admin), fields that changed with their new values. this is my code the problem is, I don't know is this best practice?, is there any package for it, how can I access the user who made changes? and of course it is not just for user table. class CustomUser(AbstractUser): __pre_save_fields = {} def _get_field_value_dict(self): return {field.attname: getattr(self, field.attname, None) for field in self._meta.concrete_fields} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__pre_save_fields.update(self._get_field_value_dict()) def save(self, **kwargs): in_memory_field_value_dict = self._get_field_value_dict() changed_fields_new_value_dict = dict( filter(lambda t: self.__pre_save_fields[t[0]] != t[1], in_memory_field_value_dict.items()) ) super().save(**kwargs) self.__pre_save_fields.update(self._get_field_value_dict()) if changed_fields_new_value_dict: UserChangeLog.objects.create(insert_edit_by_user_id=1, last_data=str(changed_fields_new_value_dict)) class UserChangeLog(models.Model): datetime_created = models.DateTimeField(auto_now_add=True) insert_edit_by_user = models.ForeignKey(AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) last_data = models.TextField() -
centos7 django codes not showing
I wrote my codes. I took them to the server and along with that, I did the operations on this site (http://wiki.centos-webpanel.com/how-to-deploy-django-apps-using-apache-with-mod-wsgi-and-nginx). I am encountering this problem. How can i solve it. sites:www.diyetzone.com -
Django three-way pivot relationship?
im trying to make a setup that i'm unsure how to implement. Basically there are three tables: Cars(main data like name etc) Categories CarOptions (eg automatic. This table holds different option names) I want the user to be able that based on the category to have the option to select the options(user may select multiple categories). Hope what i wrote makes sense, so basically a "pivot" table is needed(or is there a better way?) with data: carId categoryId optionId Thank you -
What am I doing wrong in Django?
I'm following the Django tutorial on W3 Schools step by step, but am getting this at the views class. https://i.stack.imgur.com/xP0Ib.png -
How to call a python function from views.py in html template
I'm beginner with Django Framework and I need to finish a project. Right now I'm stuck on something. Please, someone help me. I'm redering a template "borrow.html". In html code I want to call a function from views.py. I tried like this: This is views.py: def borrowBook(request): return render(request,'app_system_borrow/borrow.html', {'infoBorrowCode': infoBorrowCode()}) def write_read_file(): filepath='app_system/utils/output_QRscan.txt' with open(filepath,'r') as ff: file_content=ff.read() file_content=file_content.strip() return file_content def infoBorrowCode(): file_content=write_read_file() books=apps.get_model('app_common','Book') items_book=books.objects.all() for i in items_book: if(i.label == file_content): return redirect('info-borrow/') return "doesn't exist" def infoBorrow(request): print("dhskld") return render(request,'app_system_borrow/info-borrow.html') This is borrow.html: {% extends "base_system.html" %} {% block title %}CONTILIB{% endblock title %} {% block content %} <div class="interaction-container"> <div class="bot-interaction"> <p>Please scan the <b>QR code</b> of the book.</p> </div> </div> {% endblock content %} {{ infoBorrowCode }} This is urls.py: urlpatterns = [ path("favicon.ico",RedirectView.as_view(url=staticfiles_storage.url("img/avicon.ico"))), path('', views.borrowBook, name="borrowURL"), path('info-borrow/', views.infoBorrow), ] I put some prints in infoBorrowCode() function from views.py to see if the function is called and it is, but after return redirect('info-borrow/'), the print from infoBorrow(request) function doesn't work. It doesn't print anything. So, I think my version isn't good. Can someone exaplin what I'm doing wrong? Please.. Or if there is another option for it.. -
Twilio Incoming SMS Webhook for Admin Access URL
I have configured and have the code written out in my Django app to integrate Twilio SMS sending and receiving. It is successfully sending messages. However, the problem I'm coming across is that the public facing URL I have to communicate with the webhook and TwiML is only accessible for the admin so you have to have a certain authentication to access the messaging dashboard (where the messages are coming in). I'm not sure how to configure this in Twilio I was wondering how I can configure this webhook in Twilio to ensure a user can respond via SMS from their phone and the message will display in the messaging dashboard within the app. I'm not super familiar with Twilio or this situation so any help would be greatly appreciated. Thanks in advance! -
why im getting invalid client error while trying to post in postman
hi i was trying to post in postman using some parameters like client_id and client secret and token which i got it from Facebook[enter image description here][1] developer app `hi i was trying to post in postman using some parameters like client_id and client secret and token which i got it from Facebook[enter image description here][1] developer app ` #here is my reqest url:http://localhost:8000/api/social/convert-token?grant_type=convert_token&client_id=sdklhsjgvdshfuahhddkaj37637utydew7&client_secret=dgshjhsdfkgaskflj8363589klsskjnlksfjnljhfjmj83889ij&backend=facebook&token=lkdfjlkjhdsfkljhbdsncvkjdsh763uhkdjcbgjhxsgckjdsh7ytfgklfclkfoit76ejvmljfdlkjndsi736uihd #postman [1]: https://i.stack.imgur.com/lMQD8.png #also my setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-0-4)4j%h!n^v@h0fhyk*7b&-za)tliaptb^kqs$5#+=3tns%=+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'coreapp', 'cloudinary', 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'foodhub.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'foodhub.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
How to relate multiple models to a single model in Django?
I want to store all the data related to a specific device, and I called the model that stores that information File. But for example a device with Motherboard, have multiple fields only related to the motherboard(model, brand, serie's number), and so on with the cpu, gpu, mouse, etc. Is there a way to include multiple models inside a model and create a form that join all of them inside the File model? Like this: class File(models.Model): institute = models.CharField(max_length=200) motherboard = models.ForeignKey(Motherboard, on_delete = models.CASCADE) cpu= models.ForeignKey(Cpu, on_delete = models.CASCADE) The problem I having with this aproach is that the create view just showed me a dropdown list in the motherboard and cpu fields, waiting for me to select one of the already existing ones, the expected behavior is the view displaying a form for each of the models and be able of see all the information as a whole under the File model. -
Get all children of self-referencing Django model in nested hierarchy
Introduction We’re currently working on a Django REST Framework project. It connects to a Postgres database that holds some hierarchical (tree structure) data, that goes a number of levels deep. We should offer an endpoint for GET requests that returns the entire nested tree structure (parent, children, grandchildren etc.) when no parameter is offered. ATTENTION: Please do not mark this as a duplicate straight away, without reading the complete question. There are already very similar questions and I already tried the answers to those. I mention these in my post and what problems I face when trying these. Sample data The table below shows the sample data of regions, where each region can have a parent, indicating the hierarchy of regions. In this example, the hierarchy is three levels deep (world>continent>country). But in reality, the tree could go much deeper, having an unknown number of levels (world>continent>country>province>city>neighborhood>etc.). id region parent_region_id 1 world NULL 2 europe 1 3 asia 1 4 africa 1 5 belgium 2 6 germany 2 7 spain 2 8 japan 3 9 indonesia 3 10 vietnam 3 11 tanzania 4 12 egypt 4 13 senegal 4 Our goal The JSON output shown below is what we try … -
Change the user input on django change form before sending it to the database
I have a model that has a uuid representing a certain region. There is a short name for the regions and their respective uuid, this is stored in a csv currently. Is there a way to allow an admin to use the short name instead of the uuid when editing a record, but the uuid is what is actually used in the database? Current: Current edit form Desired: Desired edit form -
Django rest framework Like Function
in django, I want to write a function that deletes the likes if the current user has liked that post before and if so, how can I do this. This is my models.py class Like(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.created_by.username This is my serializers.py class LikeSerializer(serializers.ModelSerializer): created_by = serializers.StringRelatedField() post = serializers.StringRelatedField() post_id = serializers.IntegerField() class Meta: model = Like fields = ('__all__') This is my views.py class LikesView(viewsets.ModelViewSet): queryset = Like.objects.all() serializer_class = LikeSerializer def perform_create(self, serializer): serializer.save(created_by=self.request.user) This is my urls.py from django.urls import path,include from .views import ( PostView, PostView_View, LikesView, CommentView ) from rest_framework import routers router = routers.DefaultRouter() router.register('likes', LikesView) router.register('post', PostView) router.register('comment', CommentView) urlpatterns = [ ] + router.urls -
How to perform the Django unit test more efficiently on its python complex classes and functions?
I have gone through the Django test case documentation. But only found the case of the simple basic. https://docs.djangoproject.com/en/4.1/topics/testing/overview/ I will be grateful if someone enlightens me with advanced know-how related to unit tests and pytest. -
Cannot makemigrations on Django Settings already configured error
I'm a new django developer and I recently started a project, and am trying to get the database up and running. For background: we are using a mysql database for storage, and the settings are configured for it. Using an Unbuntu DO server. I have also been using the virtual environment to run the commands below. When we initially created the project we ran the makemigrations command, which populated the database with django tables, but not the Models, as we had not made any Models yet. I've now uploaded the Model code, however I could not make any new migrations, I got the error RuntimeError("Settings already configured"). According to this tutorial which I was following (https://www.geekinsta.com/how-to-customize-django-user-model/) some errors are normal and required me to delete and recreate the mysql database (which I did, it has the same name), and clear past migrations (the app/migrations/pycache is now empty). However I'm still experiencing the same error ("Settings already configured"). How can I fix this? I need to successfully run the makemigrations and migrate commands to populate the database. The new database and pycache are empty after I attempted the commands again. Thanks for any and all help. -
Token expiry error when using SimpleJWT TokenVeryifySerializer to return user data
I have a backend API app that uses DRF and SimpleJWT as the Auth engine. The React front-end that consumes the auth API requires an end-point that will accept an access token, verify it and return the token object and associated user object. I am looking to extend SimpleJWT's existing TokenVerifySerializer to do this as it already contains the verify and blacklist logic. I'm hitting a wall when trying this as I keep receiving a Token is invalid or expired error even if the token is valid Any pointers to where the problem may be would be greatly appreciated! Code is as follows: # apiauth/serializer.py from django.contrib.auth.models import User from django.apps import apps from django.contrib.auth.password_validation import validate_password from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework import serializers from rest_framework.validators import UniqueValidator from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenVerifySerializer from rest_framework_simplejwt.settings import api_settings from rest_framework_simplejwt.tokens import RefreshToken, SlidingToken, UntypedToken, AccessToken if api_settings.BLACKLIST_AFTER_ROTATION: from rest_framework_simplejwt.token_blacklist.models import BlacklistedToken class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['email'] = user.email return token class TokenUserSerializer(TokenVerifySerializer): token = serializers.CharField() def validate(self, attrs): access_token = UntypedToken(attrs["token"]) if ( api_settings.BLACKLIST_AFTER_ROTATION and apps.is_installed("rest_framework_simplejwt.token_blacklist") ): jti = access_token.get(api_settings.JTI_CLAIM) if BlacklistedToken.objects.filter(token__jti=jti).exists(): raise ValidationError("Token is blacklisted") token = AccessToken(access_token) user = User.objects.get(access_token['user_id']) …