Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Forbidden (403) CSRF verification failed. Request aborted. django error
I want to post a form with HTML <form method="POST" enctype="multipart/form-data"> {% csrf_token %} // some inputs </form> My middlewares are these MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] When I try to post a form, it is showing the following error Forbidden (403) CSRF verification failed. Request aborted. -
Installation of Spatialite with Django on windows 10
I am struggling to find out how to install spatialite for geodjango on windows but I don't know what I am doing wrong. I follow the instructions as per the django page https://docs.djangoproject.com/en/4.0/ref/contrib/gis/install/spatialite/ but the tutorial doesn't say what to do after getting the binarys of spatialite I have tried to put them everywhere but every time I get the same error: Exception Value: Unable to load the SpatiaLite library extension as specified in your SPATIALITE_LIBRARY_PATH setting I tried to put the mod_spatialite.dll file everywhere and try to set to SPATIALITE_LIBRARY_PATH but it seems I can't get the solution Any suggestions would be appriciated Thanks -
Django multiple upload drag and drop not working
I want to do an update on a current web app I developed with Django. The current version has multiple uploading fields: And I changed it to this: Now I don't know how to update the code to do exactly the same thing, I made some changes, but I can't seem to get the files from the dropzone using request.FILES.getlist('files') Here is my old code: HTML: <h5>Documents de base</h5> {{ formset.management_form }} {% for form in formset %} {{ form|crispy }} {% endfor %} View: ................... if request.method == "POST": dossierForm = DossierForm(request.POST) formset = DocumentFormSet( request.POST, request.FILES, queryset=DocumentdeBase.objects.none() ) formset2 = PhotoAvantFormSet( request.POST, request.FILES, queryset=PhotoAvant.objects.none() ) if dossierForm.is_valid() and formset.is_valid() and formset2.is_valid(): ................... for form in formset.cleaned_data: # this helps to not crash if the user # do not upload all the photos if form: image = form["documentdebase_image"] photo = DocumentdeBase( dossier=dossier_form, documentdebase_image=image ) photo.save() for form2 in formset2.cleaned_data: # this helps to not crash if the user # do not upload all the photos if form2: image2 = form2["photoavant_image"] photo2 = PhotoAvant(dossier=dossier_form, photoavant_image=image2) photo2.save() .................... else: dossierForm = DossierForm() formset = DocumentFormSet(queryset=DocumentdeBase.objects.none()) formset2 = PhotoAvantFormSet(queryset=PhotoAvant.objects.none()) Form: class DocumentdebaseForm(forms.ModelForm): documentdebase_image = forms.ImageField(label="") class Meta: model = DocumentdeBase fields = … -
Django Admin disable a html field by a another field value
I have a django model and I want to disable the other field according to the selection of one field in my admin panel. Look at the picture if the "User Auth Filter" field is "Only Unauthenticated Users", I want the "Linkedin Filter" field to be disabled from html. like this: How can I do the "disabled html" operation before saving from the admin panel. -
Django & React integration without using an API
Is there anyway to use django and react while keeping the business logic, routing, etc on the django side ? I want to use react for the ui features and the state management but on the other hand i don't like to do the business logic on the front end and just use drf as an api for the data. The way i would imagine it is to render mini react apps instead of django templates but i have no clear way to implement this and i don't even know if it's technically possible. I would like to get some guidance from more experienced developers. Thanks -
Django throws "connection to database already close" error on Scrapy + Celery task
Context I have a Django application running inside a Docker container. This application uses Celery and Celery-beat for async and scheduled tasks. One of those tasks scrapes texts from different webs using Scrapy. This task runs every minute looking for new texts on the pages. If there is new information, it creates a new object in MyModel. This logic (querying the database to check if data exists, and create the object or update the info) is performed by a custom Scrapy item pipeline. Issue When using Development environment (using locally Docker Compose to turn on one container for the app, one container for PostgreSQL plus other services containers) everything runs smoothly. However, when using Stage environment (one Docker container for the app on a DigitalOcean droplet and a PostgreSQL self-managed cluster) the tasks throws this error: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 236, in create_cursor cursor = self.connection.cursor() psycopg2.InterfaceError: connection already closed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/twisted/internet/defer.py", line 857, in _runCallbacks current.result = callback( # type: ignore[misc] File … -
Django: Create a superuser in a data migration
Goal: automatically creating a superuser I'm trying to create a default user, specifically a superuser, in an early data migration, so whenever my Django application is run in my Docker container, it already has a superuser with which I can access the admin site. I had already tried different options for creating said superuser, and although I have some functioning ones (based on the command parameter of my docker-compose file), I've seen when adding initial data to a Django project, the best practice is to do it through a Data Migration. My custom user In my Django project I've extended the AbstactBaseUser so I can change the default username field requirement for the email field. My User is as such: class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): # Implementation... def create_superuser(self, email, password, **extra_fields): # Implementation... class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name="email address", max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email Failed attempts By following the Django documentation here I tried making my superuser in a data migration with the following code, located in a file called 0002_data_superuser in the migrations folder of my app: … -
Deploying FrontEnd and BackEnd as two separate applications with Google Cloud App Engine
I have two application that I want to deploy with Google Cloud App Engine. One of them is react front end, and I want to serve this through www.videoo.io Second one is back-end, which will be served via api.videoo.io Frontend yaml file react.yaml : runtime: nodejs16 env: standard handlers: - url: /static static_dir: static secure: always - url: www.videoo.io/* service: frontend script: auto secure: always% API yaml file, api.yaml : runtime: python37 entrypoint: gunicorn -b :$PORT videoo.wsgi service: "videoo-api" env: standard handlers: - url: api.videoo.io/* service: backend script: auto secure: always% Is this the correct way to achieve this ? What is the best strategy to serve these two separate applications that will interactively communicate (Frontend will make calls to API to get object information that is stored Django app) ? Here is also my domain name information in Google App Engine settings : -
Django kwargs doesn't retrieve value after page reload
I got this code in my view. @login_required(login_url='login_user') def user_profile(request, **kwargs): user = request.user post_form = PostForm(instance=user) post_func = post(request) user_n = kwargs.get('username') READ THIS PLEASE! user_n it returns the username of the current user, but for some reason, after I create posts with the post function it doesn't get the username, but it gets str:username instead when I print it to console. Does anyone know why and how I can fix this? print("This is the user logged in: ", user.username, user_n) EXAMPLE for the print above("This is the user logged in: ", user.username = current username, user_n = str:username (this is happening only when I use the post function to post some content. Any other time user_n = current username)) user_data = {} try: current_user_username = NewUser.objects.get(username=user_n) current_user_profile = Profile.objects.get(relation_id=current_user_username.id) except: return redirect("profiles") is_self = True if current_user_username: current_profile_posts = Posts.objects.filter(post_relation_id=current_user_username.id) user_data['current_profile_id'] = current_user_username.id user_data['current_profile_username'] = current_user_username.username user_data['current_profile_email'] = current_user_username.email user_data['current_profile_title'] = current_user_profile.title user_data['current_profile_avatar'] = current_user_profile.avatar user_data['is_self'] = is_self else: pass if post_func is not None: print("If post_func is not none: ", post_func) return post_func elif post_func is None: print("If post_func is none: ", post_func) pass else: print("This state of post_func should never activate: ", post_func) return http.HttpResponseRedirect('/UserProfile/<str:username>/') context … -
by inheriting the class base view, my own form does not work in django
I write my own login form inheriting LogonView, with my own Form. My own form does not have a password field! because I send a temperory password to the email given by a user. But when I inherit LoginView, the form has 2 fields : username and password. If I inherit CreateView instead of LoginView, instead of displaying profile, it returns: User matching query does not exist. I am newdeveloper. Your help is appreciated. -
Django Rest Framework: KeyError when Overriding 'update' Function in a Serializer
I have a User model and a Group model, which are presented below: class User(models.Model): username = models.CharField(primary_key=True, max_length=32, unique=True) user_email = models.EmailField(max_length=32, unique=False) user_password = models.CharField(max_length=32) user_avatar_path = models.CharField(max_length=64) class Group(models.Model): group_id = models.AutoField(primary_key=True) group_name = models.CharField(max_length=32, unique=False) group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='my_groups') members = models.ManyToManyField(User, related_name='groups', through='UserGroup') Every group can have multiple users associated with it and every user can be associated to multiple groups, which is modeled with a ManyToManyField and a through model between the models. When I create a group, the user which creates the group is automatically assigned as the group admin and therefore added as a member of the group: class MemberSerializer(serializers.ModelSerializer): # The nested serializer used within the GroupSerializer username = serializers.ReadOnlyField(source='user.username') class Meta: model = User fields = ['username'] class GroupSerializer(serializers.ModelSerializer): members = MemberSerializer(source='user_groups', many=True, required=False) group_admin = serializers.SlugRelatedField(slug_field='username', queryset=User.objects.all()) # A Group object is related to a User object by username class Meta: model = Group fields = ['group_id', 'group_name', 'group_admin', 'members'] def create(self, validated_data): # Overriden so that when a group is created, the group admin is automatically declared as a member. group = Group.objects.create(**validated_data) group_admin_data = validated_data.pop('group_admin') group.members.add(group_admin_data) return group def update(self, instance, validated_data): members_data = validated_data.pop('members') # … -
Function of defining an absolute URL in a model in Django
I am currently completing the final capstone project for Django on Codecademy, and I've come across a comprehension issue. On Codecademy, they state that it's used to redirect to the homepage when a user submits data, while the Django documentation for get_absolute_url seems to make no reference to redirects. I currently have no absolute urls defined for any of my models, and these are my url patterns and views. At this stage, I'm just trying to understand the purpose of defining an absolute URL in a model, and where the appropriate places to utilize it are. I'm very confused about it's function currently, and would appreciate a simplified explanation with examples. -
Django Rest API is producing 500 status code
I am tasked with creating a Django Rest API containing a serializer. Here is the specific instructions: Instructions Here is my model.py: from django.db import models class Wish(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100,blank=True,default='') wishtext = models.TextField() class Meta: ordering = ('created',) My serializers.py: from rest_framework import serializers from wishes.models import Wish #Add WishSerializer implementation here class WishSerializer(serializers.Serializer): created = serializers.DateTimeField() title = serializers.CharField(max_length=100, default='') wishtext = serializers.CharField() my views.py: from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse,HttpResponse from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse,HttpResponse from rest_framework.response import Response from rest_framework.parsers import JSONParser from wishes.models import Wish from wishes.serializers import WishSerializer @csrf_exempt def wish_list(request): pass """ List all wishes or create a new wish """ if request.method == 'GET': qs = Wish.objects.all() serializer = WishSerializer(qs, many=True) return Response(serializer.data) if request.method == 'POST': serializer = WishSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) @csrf_exempt def wish_detail(request,pk): pass """ Retrieve, update or delete a birthday wish. """ try: wish = Wish.objects.get(pk=pk) except Wish.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = WishSerializer(wish) return Response(serializer.data) elif request.method == 'PUT': serializer = WishSerializer(instance=wish, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) elif request.method == 'DELETE': wish.delete() return Response(status=204) and my url.py: from django.conf.urls import url … -
question about counting time calculated by property
I have created a date and time delta property. this property calculates the total time between two date and times for a job. Now I want to create a property that sums all the time of the jobs and represents it on a card. I have tried many ,but no success. Hopefully someone has a solution @property def Get_time_diference(self): start_time = self.date end_time = self.dateTo total = end_time - start_time return total -
Google Book api , gTTs, googletrans, PyPDF4
I have used Google Book API, gTTs, googletrans, and PyPDF4 in my Django Project. I am trying to draw a Deta Flow Diagram of my project. I am confused about the diagram should I draw like please help me to figure it out -
Which database in the backend should be used for a personal website/blog? [closed]
I want to create a personal website (to learn) and post there various articles. I wonder if I need a database to store these articles. I think it would be nice to have them stored somewhere separately instead of e.g. straight in the hmtl files. Then it would be possible to port these articles elsewhere. However I do not have enough practical knowledge to choose a sensible approach. Right now I am thinking of using SQLite. However, I also want the visitors of my website to leave comments, so to store those I assume I would need something bigger/better? Main points: there will be some dynamic content such as comments from users I do not want to allow visitors to register or port articles, only comment I want visitors to "log in" (to be able to leave a comment) via their social media accounts e.g. Google account I realise these comment and the visitors login information needs to be stored somewhere What is the sane approach to have a database for the personal website? -
Handling an Items catalogue with variable attributes
I am a beginner to Django and I have more of a conceptual question (so I have no code yet). I am currently trying to assemble a catalogue of items through a model called Item. One of the fields that I have in this Model is item_type. Each item_type will have different relevant properties(which in this case would be fields). For example, if it is a pump I would be interested in the nominal pressure, but if it is a boiler I am interested in the heating capacity. What would be the best way of approaching such a case? I was thinking about two solutions: Adding all the possible properties in the Item model and only filling in the relevant ones. However, this would create a problem as I do not want to show the user all these fields when creating a new item through the form. Ideally, I would like to have only a few fields that are common (the name of the item for example), and then, after selecting the item_type the form is extended with the relevant fields of that component type. However, I am not sure how I would be able to achieve this exactly and … -
CSS file don't connecting with HTML (Django)
index.html I have changed {% static "/main/css/index.css" %} to {% static "main/css/index.css" %} {% extends 'main/base.html' %} {% load static %} <link rel = 'stylesheet' type="text/css" href="{% static "/main/css/index.css" %}"/> {% block title %} {{title}} {% endblock %} {% block content %} <body> <div class="grid-wrapper"> <header class="grid-header"> <img class="circles" src="{% static "main/img/main8.jpg" %}" alt="main pic"> <p>hello</p> </header> </div> </body> {% endblock %} index.css .grid-wrapper { display: grid; grid-template-columns: 1 fr; grid-template-rows: 1 fr; grid-template-areas: 'header header'; } .circles { display: block; margin-left: auto; margin-right: auto; } header { position: relative; width: 100%; } p { color: red; text-align: center; position: absolute; width: 100%; text-align: center; top: 0; } settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "main/static"), ] [file's location] I tried changing file names, changing locations, connecting in a different way, but all this does not work. I also changed the settings. -
Why I'm Getting error when I run workon command?
I'm Totally newb in Django! everytime I get error when I run workon even I install workon module but it didn't help me whenever I run python -m workon test it shows me No module named workon! any solution? best regards Nafiz -
dj-rest-auth Reset email link keeps pointing to the backend
I'm using dj-rest-auth with react and i'm trying to use the frontend url instead of the backend url. The solution i am using for the account creation confirmation email affects the reset password email too but only partially. It does not effect the port. It only tries to add a key to the reset link where there is none and throws me an error. So i was wondering if there is a way to change the url from port 8000 to port 3000. This is what i have tried: class AccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request: HttpRequest): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) def send_mail(self, template_prefix, email, context): if settings.DEBUG: context["activate_url"] = ( "http://localhost:3000/accounts/confirm-email/" + context["key"] ) else: context["activate_url"] = ( settings.FRONTEND_URL + "/accounts/confirm-email/" + context["key"] ) return super().send_mail(template_prefix, email, context) If i get rid of the key part it doesn't give me an error but keeps port 8000 and breaks my account confirmation emails. If i don't get rid of the key it gives me: django | "http://localhost:3000/accounts/confirm-email/" + context["key"] django | KeyError: 'key' -
Django contenttypes follow/unfollow
Trying to use contenttypes to store following relations of users. I can create a follow, but I can't remove a follow from the database. Model Code accounts app ------------ from activities.models import Activity class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) follow = GenericRelation(Activity) activities app -------------- class Activity(models.Model) FOLLOW = 'F' LIKE = 'L' ACTIVITY_TYPES = [ (FOLLOW, 'Follow'), (LIKE, 'Like'), ] ## stores the user_id of the Liker/Follower user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ## stores 'F' or 'L' activity_type = models.CharField(max_length=2, choices=ACTIVITY_TYPES) date = models.ForeignKey(ContentType, on_delete=models.CASCADE) ## stores CustomUser id of the user who is followed or the id of the post that is liked object = models.UUIDField(null=True, blank=True, db_index=True) content_object = GenericForeignKey('content_type', 'object_id') class Meta: indexes = [models.Index(fields=["content_type", "object_id"]),] View Code follower = User.objects.get(id=follower_id) followed = User.objects.get(id=followed_id) ## This is the contenttypes model a = Activity.objects.filter(user=follower.id, object_id=followed.id) ## This is my janky way of checking whether the follower is already following the followed if len(a) == 0: ## This works to create a follow followed.follow.create(activity_type=Activity.FOLLOW, user=follower) I thought this might work to delete the follow followed.follow.remove(a) but it gives me an error 'QuerySet' object has no attribute 'pk' -
The current path, accounts/login/, didn't match any of these
Ive been trying to implement the reset password processs of django but something is not working, I know from the error that there is a url pattern that does not exit but from where accounts/login came from,It worked fine before but my colleague took my laptop and after that this happened urls.py """travel URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('',include('loginpage.urls')), path('signup/',include('signup.urls')), path('homepage/',include('Homepage.urls')), path('password_reset/',auth_views.PasswordResetView.as_view(template_name='loginpage/resetpassword.html'),name='password_reset'), path('password_reset_sent/',auth_views.PasswordResetDoneView.as_view(template_name='loginpage/password_resent_sent.html'),name='password_reset_done'), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='loginpage/password_reset_form.html'),name='password_reset_confirm'), path('Password_changed_succesfully/',auth_views.PasswordResetConfirmView.as_view(template_name='loginpage/password_reset_done.html'),name='password_reset_complete') ] resetpassword.html: <!DOCTYPE html> <html> <head> {% load static %} <title>Reset Password</title> <link rel="stylesheet" type="text/css" href="{% static 'reset.css' %}"> <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css" /> </head> <body> <div class="right"><img src="{% static 'images/logo2.png' %}" height="400" width="400"></div> <div class="main"> <input type="checkbox" id="chk" aria-hidden="true"> <div class="resett"> <form … -
Iam Created Login Form but here If I login twice only it redirects the page in django
Here My Html Code I am created an Login Form Here my action is empty if I give an URL in action means. Then I will submit means it will goes to next page without authentication. Please Help me out...If I am login means it will redirect to the Page Dash. But here i want to login twice only means then it works successfully...If I login only once means it does'nt redirect the page I don't know why <form action="" method="post"> {%csrf_token%} <div class="form-outline mb-4"> <input type="text" name="username" id="form3Example3" class="form-control form-control-lg" class="form-control new-input" placeholder="Enter a Name" required> <label class="form-label" for="form3Example3"></label> </div> <div class="form-outline mb-3"> <input type="password" name="password" id="form3Example4" class="form-control form-control-lg" placeholder="Enter password" required> <label class="form-label" for="form3Example4"></label> </div> <div class="d-flex justify-content-between align-items-center"> <div class="form-check mb-0"> <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3" /> <label class="form-check-label" for="form2Example3">Remember me</label> </div> <a href="#!" class="text-body">Forgot password?</a> </div> <div class="text-center text-lg-start mt-4 pt-2"> <input type="submit" value="submit" class="register-button2" /> </form> <p class="small fw-bold mt-2 pt-1 mb-0">Don't have an account? <a href="{% url 'register'%}" class="link-danger">Register</a></p> </div> Views.py def Login(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: request.session['user'] = username auth.login(request,user) print(user) return redirect('Dash') else: messages.info(request,'invalid credientials') return redirect('Login') else: return render(request,'Login.html') This is the Dash View … -
Registration data "lost" somewhere in python django 4
I have my super basic authentication app, and I tried to write a simple Registration with email, first name, last name and (logically) password, but it seems that when I enter my request data it is "lost" somewhere. When I press the "POST" button, all the fields are blank and it says: "This field is required". I've been trying to figure it out for quite a long time, but I am new to django. I hope you can spot the problem. Here is my models.py: class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password=None): if first_name is None: raise TypeError('Users must have a first name') if last_name is None: raise TypeError('Users must have a last name') if email is None: raise TypeError('Users must have an email') user = self.model(email=self.normalize_email(email), first_name=first_name, last_name=last_name) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager My serializers.py: class RegistrationSerializer(serializers.ModelSerializer): token = serializers.CharField(max_length=255, read_only=True) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password', 'token'] def create(self, validated_data): return User.objects.create_user(**validated_data) And my views.py: class RegistrationAPIView(APIView): permission_classes = (AllowAny,) serializer_class = RegistrationSerializer def … -
How to add custom field when verifying access token in rest_framework_simplejwt
I tried to override validate method at TokenVerifySerializer but this raises AttributeError. from rest_framework_simplejwt.serializers import TokenVerifySerializer from rest_framework_simplejwt.views import TokenVerifyView class CustomTokenVerifySerializer(TokenVerifySerializer): def validate(self, attrs): data = super(CustomTokenVerifySerializer, self).validate(attrs) data.update({'fullname': self.user.fullname}) return data class CustomTokenVerifyView(TokenVerifyView): serializer_class = CustomTokenVerifySerializer But that does work when using TokenObtainPairSerializer and TokenObtainPairView. The above snippet raises AttributeError with 'CustomTokenVerifySerializer' object has no attribute 'user'.