Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django debug toolbar 404
I am trying to get django-debug-toolbar working. I have followed the installation steps and I get the sidebar including stats (e.g. SQL 1 query in 2.75ms, Static Files 19 Files used, 30 receivers of 12 signals) which seem to be legitimate and indicate that its working. However, when I click for more info on a given tab, I get a 404 in browser, and this sort of thing in the console: "GET /__debug__/render_panel/?store_id=ac74875cfe864b2dab4c6d17c1d1ed5d&panel_id=RequestPanel HTTP/1.1" 404 1791" Other pages on site do work. I have tried various configurations in urls.py. Here is what I currently have: from __future__ import absolute_import, unicode_literals from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from search import views as search_views urlpatterns = [ url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), # For anything not caught by a more specific rule above, hand over to # Wagtail's page serving mechanism. This should be the last pattern in # the list: url(r'', include(wagtail_urls)), # Alternatively, if you want Wagtail pages to be served from a subpath # of your site, rather than the … -
Django: Extent with snippets or better solution
I have the following template: {% extends "account/base.html" %} {% load i18n %} {% load account %} {% load crispy_forms_tags %} {% block head_title %}{% trans "Password Reset" %}{% endblock %} {% block content %} <div class="container"> <div class="row justify-content-center"> <div class="col-8"> <h1>Reset your password</h1> {% if user.is_authenticated %} {% include "account/snippets/already_logged_in.html" %} {% endif %} <p>{% trans "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}</p> <form method="POST" action="{% url 'account_reset_password' %}" class="password_reset"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Reset My Password</button> </form> <p><em>{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}</em></p> </div> </div> </div> {% endblock %} account/base.html contains this here: {% extends "base.html" %} base.html then contains tags etc. I am currently struggling with finding the best solution while considering DRY. In my template I have written: <div class="container"> <div class="row justify-content-center"> <div class="col-8"> [more text] </div> </div> </div> I have several of these templates and in each of them I am currently writing the same ... I am now wondering is the right solution to include these opening / closing div-tags in two files and then … -
Pre-populate HTML form table from database using Django
I have a class-based view (IndexView at views.py) that shows a table with all the data stored in the database. This view is rendered in index.html using a def get_queryset(self) to obtain all the data. No issues yet. The difficult part for me is trying to do it using a form, to be able to modify and save the amount column. I have no issues with the POST part, where I use AJAX to save the new values. Where I'm having issues is getting the initial values from the database to populate a Django Form (forms.py) I tried using initial argument in the definition of the form fields (at forms.py), even overriding __init__ at the form definition, but I don't know how to get "one value". I mean, the closer I've been in my tests was populating a MultipleChoiceField with: forms.ModelMultipleChoiceField(queryset=Item.objects.order_by('code__name')) (achieving a multiple choice field of Item object (1), Item object (2), etc.) But how do you populate a single IntegerField or CharField with the content of the database to show a form-based table field in the template? I'm trying first with a single item (to try to understand how to reference one item/value to populate them using the … -
Unable to import view .. Python Django
i donot why app registery error is showing when i try run the url.py in music folder i see this error also view not getting imported when i try running the website urls, i get this above errors, i tried searching for solution in this website.. couldn't get the proper ans please help to resolve this soon team. -
Python // coming from SQL server table with /
I have a field in my SQL server table that is a varchar that is coming into my model defined as field= models.CharField(db_column = 'tablename', max_length = 30) When I look at the POST coming through my field is displayed as AAA//AAA#### when it's stored in the database as AAA/AAA####. Later in my view I try to call the field, but it's attempting to divide giving the following error: ValueError: invalid literal for int() with base 10: 'AAA\\AAA####' How can I get this field to display as AAA/AAA#### in my post? owner = request.POST.get('usercheck') -
Arrayfield in Django
my code: pagerange_str_array = ArrayField(models.CharField(max_length=10, blank=True, default=list())) docs example: https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/ board = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, ) docs - size: This is an optional argument. error message: DETAIL: Array value must start with "{" or dimension information. But none of these work: default={}, '{}',or {''} They all get the same error message. docs: If you give the field a default, ensure it’s a callable such as list (for an empty default) or a callable that returns a list (such as a function) But none of these work either: default=list, list(). null=True (my original code) also does not work. All these examples give the same error. I have seen non-Django solutions on the web, but what is an example of code that works in Django?! Thanks. -
How do I render my django login form with bootstrap?
I am struggling to understand how handling forms manually works... It's a bit of a headache because there are no relevant examples, or they are outdated. I just have the basic login form with username and password. I would like to display the errors under each field if possible. Thank you. <form method="post"> {% csrf_token %} {{ form.username }}<br> {{ form.password }}<br> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <button type="submit" class="btn btn-primary">Submit</button> </form> Right now, the above snippet display errors in such way that my whole form gets moved to the left inside the html page. -
Django docs -- CBVs: Why not just define a get() method that takes an argument from a URL?
Noob here going through the Django docs, trying to get a grip on how it all fits together. In this section of their document on generic class-based views, they demonstrate the hard-coding of filter parameters for a particular publisher (in this example) into ListView's queryset attribute and suggest that doing so will become problematic once you need separate ListViews for every publisher. That makes sense to me. In the next section they suggest overriding ListView's get_queryset() method this way: class PublisherBookList(ListView): template_name = 'books/books_by_publisher.html' def get_queryset(self): self.publisher = get_object_or_404(Publisher, name=self.kwargs['publisher']) return Book.objects.filter(publisher=self.publisher) My question is, why not just declare a get() method in ListView and allow get() to take in publisher from the URL? What am I missing here? -
class based view passing parameters
I have just started using Class-based views and I am trying to pass the parameters to class-based view as: return HttpResponseRedirect(reverse('myView'), kwargs={'method': 'learning'}) My view is: class MyView(View): form_class = MyForm initial = {'key': 'value'} template_name = 'algoRunning.html' def dispatch(self, request, *args, **kwargs): print (kwargs['method']) data = self.readFile('myFile.txt') context = {'result': data} return render(request, self.template_name, context) def readFile(self, filePath): # read data return data my url pattern looks like: urlpatterns = [... url(r'^learning/(?P<method>[a-z]+)/$', my_views.MyView.as_view(), name='myView'), ..] But, it gives me following error Reverse for 'myView' with no arguments not found. 1 pattern(s) tried: ['learning/(?P<method>[a-z]+)/$'] What am I doing wrong?? -
AssertionError: `base_name` argument not specified
i'm trying to add a parameter of a model to a URL pattern, as such: http://111.111.11.111:8080/resultados/image.jpg where nome_ficheiro = image.jpg (nome_ficheiro is a model parameter, see below) But i'm getting the following error: File "/usr/local/lib/python2.7/dist-packages/rest_framework/routers.py", line 139, in get_default_base_name assert queryset is not None, '`base_name` argument not specified, and could ' \ AssertionError: `base_name` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. The URL pattern: router = routers.DefaultRouter() urlpatterns = [url(r'^', include(router.urls))] router.register(r'resultados/(?P<nome_ficheiro>.+)/$',resultUploadView.as_view({'get': 'get_queryset'})) The view: class resultUploadView(generics.ListAPIView): serializer_class = resultSerializer queryset = labelResult.objects.all() def get_queryset(self): nome = self.kwargs['nome_ficheiro'] return labelResult.objects.filter(nome_ficheiro=user) The model: class labelResult(models.Model): nome_ficheiro = models.CharField(max_length=120) especie = models.CharField(max_length=120) zona = models.CharField(max_length=120) data = models.CharField(max_length=120) USING: Python 2.7.12 and DRF 3.6.3 -
Django ChoiceField generated from a function
I want a generic list of choices in my form. In the devices.py def get_devices(): api_url = api_url_base response = requests.get(api_url,headers=headers) if response.status_code == 200: return json.loads(response.content.decode('utf-8')) else: return None ####################################### devices_infos = get_devices() if devices_infos is not None: print('Voici les devices: ') for each in devices_infos['data']: device_name = (each['name']) for k in range(len(devices_infos['data'])): mes_choix = ("(%s, ('%s'))," % (k,device_name )) else: print("[!] Request failed") It returns me my 2 devices like that (0, ('Erics phone')), (1, ('mySensor001')), In forms.py from django import forms from alertes.devices import * class NameForm(forms.Form): nom_alerte = forms.CharField(label='Nom Alerte', max_length=100) devices = forms.ChoiceField(label='Liste devices', choices=mes_choix, required=False) user_mail = forms.EmailField(label = 'Email a envoyer', max_length=100) Here, i would have in the devices label, a list of choice like Erics phone mySensor001 But i got the need more than 1 value to unpack error -
Parent Keys in Django Template URL lookup
In Django, I am trying to make an app with a tree hierarchy of models, i.e: My Models in models.py: class Book(models.Model): name = models.CharField("Book Name", max_length = 80) class Chapter(models.Model): name = models.CharField("Book Name", max_length = 80) book = models.ForeignKey('Book', on_delete = models.CASCADE) My URL patterns in urls.py: urlpatterns = [ path('books/', views.BookListView.as_view(), name='book_list'), path('books/<int:book>/', views.BookDetailView.as_view(), name='book_detail'), path('books/<int:book>/chapters/', views.ChapterListView.as_view(), name='chapter_list'), path('books/<int:book>/chapters/<int:chapter>/', views.ChapterDetailView.as_view(), name='chapter_detail'), path('books/<int:book>/chapters/create/', views.ChapterCreateView.as_view(), name='chapter_create'), My Views in views.py: class BookListView(generic.ListView): model = 'Book' class BookDetailView(generic.DetailView): model = 'Book' pw_url_kwarg = 'book' class ChapterListView(generic.ListView): model = 'Chapter' def get_queryset(self): return Chapter.objects.filter(book = self.kwargs['book']) class ChapterDetailView(generic.DetailView): model = 'Chapter' pw_url_kwarg = 'chapter' class ChapterCreateView(generic.CreateView): model = 'Chapter' fields = ['name', 'book'] def get_initial(self): initial = super().get_initial().copy() initial['book'] = self.kwargs.['book'] return initial; In my HTML-Template used for the list of chapters, I want to have a link to create a new chapter. Currently, that template looks as follows: Template chapter_list.html: <ul> {% for chapter in chapter_list %} <li>{{ chapter.name }}</li> {% endfor %} </ul> <a href="{% url 'chapter_create' 42 %}">Add new chapter</a> Obviously, I don't want to add all new chapters to the book with ID 42, rather I would like to use the book ID from the chapter list, … -
Heroku run migrate gives server error
I pushed my application to Heroku, assign the dyno, and create the database. Now if I run: heroku run python manage.py migrate I receive the error: 'Is the server running on host 'localhost' and accepting TCP/IP connections on port 5432? but I don't want to run on my server but one the Heroku server -
Avoid Django duplicated queries without select or prefetch related
I new to Django so I have some problem with my QuerySets. I am buliding an app wihich collect many type of data from many table. Unfortunately I had an exisiting table structure so I can't modify my databse structure. To optimize my queries and find the reason of my slow loading I decided to use Django Debug Toolbar. The result was terrible, I saw that I hit the database to many times, so I want to improve my queries. I made some improvements but my page loading is still low (~6 sec). I have some query which I think can be improved, so I attach them. 1, question Here I hit the database two time, but I don't no how could be hit it once. query_all=Table.objects .filter(time_stamp__range=(before_now,now),network_id='1') .order_by('-time_stamp') query_last=Table.objects .filter(time_stamp__range=(before_now,now),network_id='1') .order_by('-time_stamp')[:1] 2, question Here I have the same problem, to select only the network 1 or 2 I have to make a new query which hit the database again. Unfortunately I in the tables there are more thousand data, so a good optimize method could be useful for me. I have read the documentation, but I can't find solution (or I missed) for these question. network_1=Table.objects .filter(time_stamp__range=(before_now,now),network_id='1') .order_by('-time_stamp') network_2=Table.objects … -
Get reverse relationship for item in a list of dictionaries
I have a list (QuerySet of 'DailyEnrollment' objects) of dictionaries that looks like this: [ {'location_id': 1, 'student_count': 780}, {'location_id': 4, 'student_count': 535}, {'location_id': 6, 'student_count': 496} ] The location_id relates to a Location object which has an attribute name Is there a simple way to iterate across this list, get each dictionaries location.name for the location_id and append it to the dictionary as location_name? I was considering a dictionary comprehension inside of a list comprehension - but I wasn't sure how Pythonic that was. Models: class Location(models.Model): name = models.CharField(max_length=50) short_name = models.CharField(max_length=50) The DailyEnrollment is data nabbed from a view built with external data class DailyEnrollment(SchoolModel): id = models.IntegerField(db_column='ID', primary_key=True) location_id = models.IntegerField(db_column='schoolID') grade = models.CharField(db_column='grade', max_length=10) end_year = models.IntegerField(db_column='endYear') run_date = models.DateField(db_column='runDate') student_count = models.IntegerField(db_column='studentCount') In the view this is how I get my Daily Enrollments # get past enrollments past_daily_enrollments = DailyEnrollment.objects.filter( run_date=datetime.strptime(since_date, '%m-%d-%Y'), location_id__lte='31', end_year='2018') I create a 'new list' of data with everything grouped on location_id, with the total student_count location_data = past_daily_enrollments.values('location_id').annotate( student_count=Sum('student_count') ) That's how I get to the issue I asked about. I have 'location_data', which is my list of dictionaries. -
Where store the Variables in Django?
my boss purchase a website make in Django, and i can see some variables using for the website. For example, the head site is a Variable, i want to insert a Google Analytics Code and other codes for the header, but i dont want to insert the code to each page, i want to insert the code in the Variable but i cant find it. I search the solution in Django website and Google, but the answers are not clear. Django where store the variables or how can i search it? Thanks. -
Registering Entry with the Admin Site with Django python "Safari
I've already activated virtual environment with source ll_env/bin/activate. I've already created the database with python manage.py migrate I've kept the server running with learning_log james$ python manage.py runserver I've already activated models in setting.py that is found in learning_log/learning_logs directory like this INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My apps 'learning_logs', ] And now I've opened another terminal window and activated another virtual environment with source ll_env/bin/activate I've already set up a superuser with the command `python manage.py createsuperuser, I've already defined the entry model I've also set all the files that are needed in models.py in learning_log/learning_logs from django.db import models class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." I've already migrated the entry model with python manage.py makemigrations learning_logs and python manage.py migrate but when I tried these command AGAIN it just now shows No changes detected in app 'learning_logs' … -
Django social auth with pipeline, email repeated
First, sorry for the bad english I am using django's social auth with pipelines to get the email from social networks, but when I login with facebook and then with google I am created two different accounts with the same email screenshot from admin site how can I avoid this by sending a message to the user, saying that there is already an account created with that mai, or directly logging in with the other account This is my code from Social auth pipelines in settings.py SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'users.utils.create_profile', #<-- Crear UserProfile 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'users.utils.get_avatar' ) -
Pass JavaScript variable into Django filter()
I have a Django filter in my views.py file: context['data_objects'] = Data.objects.filter(field=startDate) The variable "startDate" exists in a JavaScript file. Is it possible to pass a JavaScript file into the backend of my Django application. If not, are there any other ways to get data from my database based of a JavaScript variable? -
Getting unicode character 'u' in between 'key' text in Python dictionary
I am populating various metrics by executing data base views in a django view. However, I am getting the Unicode character in the key text for some in the final dictionary. I tried few things by going through internet, but not exactly clear on how to solve it. Appreciate help in this regard. ========Sample Code for a key that populates value for that key========= try: sqlQueryString = 'select * from primeApp_UniqueConsultationPatientFootFallDaily' cursor = connection.cursor() cursor.execute(sqlQueryString) statsInfo = dictfetchall(cursor) businessStats['DailyNewPatientsFootFall'] = statsInfo[0]['DailyNewPatientsFootFall'] except Exception as e: errorFlag = 1 error_record['JSONString'] = sqlQueryString error_record['ErrorMessage'] = 'getBusinessStats - Error in prepared SQL Statement or Selecting the Data:'+str(e) raw_ErrorRecord = rawErrorRecord(**error_record) raw_ErrorRecord.save() return false ================================================= Resulting Dict If you observe, some of the keys are embedded with 'u' in between their text. Such examples are "DailyNewP', u'atientsFootFall":"0" , 'AverageConv", u"ersionTime': 65 etc. Please suggest me where I am making a mistake and how to correct it. Thanks in advance. -
Django annotations using F() expressions with DateTimeFields
I want to write a custom QuerySet and Manager for a model that has a DateTimeField("installed_date" field) and an IntegerField ("expiration_days"), and I want to filter objects based on the rule " 'installed_date' plus 'expiration_days' is prior to current day" so to get objects that are currently due. For example: import datetime as dt from django.db import models from django.db.models import F, Func, ExpressionWrapper, DateField, IntegerField, FloatField from django.utils import timezone class MyQuerySet(models.QuerySet): def obsolete(self): current_date = timezone.localtime(timezone.now()) obsolete_qs = self.annotate( days_since_installed_date = ExpressionWrapper( F('installed_date')-current_date, output_field='IntegerField' ) ).filter( days_since_installed_date__lt=F('expiration_days') ) return obsolete_qs class MyManager(models.Manager): def get_queryset(self): return MyQuerySet(self.model, using=self._db) def obsolete(self): return self.get_queryset().obsolete() class MyModel(models.Model): description = models.CharField(max_length=100) installed_date = models.DateTimeField(default=timezone.now) expiration_days = models.PositiveIntegerField() obsolete = MyManager() @property days_since_installed_date = installed_date - timezone.now() When trying as before i get the error "'str' object has no attribute 'get_lookup'" Also tried this: class MyQuerySet(models.QuerySet): def obsolete(self): current_date = timezone.localtime(timezone.now()) obsolete_qs = self.annotate( days_since_installed_date = F('installed_date')-current_date ).filter( expiration_days__gt=days_since_installed_date ) return obsolete_qs Here I get "name 'days_since_installed_date' is not defined". If I encapsulate 'days_since_installed_date' in an F() expression inside the filter portion of the previous code i get "operator does not exist: integer > interval". And I've been trying a few more recipes based … -
django migration convert polygon to multipolygon [duplicate]
This question is an exact duplicate of: django change data type in migration I had a table with a column with Polygon type, I changed the type to MultiPolygon. Now I want to change the data which is in Polygon type to MultiPolygon. Is there any stored procedures or any other ways to do that? tnx -
How to return html or json from ViewSets depending on client django rest framework
I've created an APIs endpoints for mobile developers with all of the logic there. Now I need to create a web version of this app. Is it possible to not write the views specifically for this, but use already existing one in APIs? In API I am using Django Rest Framework ViewSets. Assume that this is my models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=100, blank=True, null=True) Then this is going to be my serializers.py: from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'title', 'description') read_only_fields = ('id',) viewsets.py: from rest_framework import viewsets from .serializers import PostSerializer from .models import Post class PostViewSet(viewsets.ModelViewSet): model = Post queryset = Post.objects.all() serializer_class = PostSerializer urls.py from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'posts', viewsets.Post, base_name='post') urlpatterns = router.urls I've seen this HTML & Forms in docs, but if I put renderer_classes and template_name it just renders html with the parameters that I want, but I want to have a separate endpoints for just returning json for mobile developers and rendering a user-friendly html for web version. Is it possible to do this and if it is, how … -
About django connecting MSSQL 2012 FileStream
I use MSSQL2012 「FileStream」to save images, and then connecting to django’s models.py . I set the FileStream first; and used “manage.pyinspectdb”. As below: http://arpheno.github.io/django/mssql/inspectdb/2015/11/15/Django-and-MSSQL.html Finally registered the table to admin.py, but i check to 127.0.0.1:8000/admin is Error DjangoUnicodeDecodeError How to fit it? # models.py class Filetable(models.Model): stream_id = models.CharField(unique=True, max_length=36) file_stream = models.BinaryField(blank=True, null=True) name = models.CharField(max_length=255) path_locator = models.BinaryField(primary_key=True) parent_path_locator = models.ForeignKey('self', models.DO_NOTHING, db_column='parent_path_locator', blank=True, null=True) file_type = models.CharField(max_length=255, blank=True, null=True) cached_file_size = models.BigIntegerField(blank=True, null=True) creation_time = models.CharField(max_length=34) last_write_time = models.CharField(max_length=34) last_access_time = models.CharField(max_length=34, blank=True, null=True) is_directory = models.BooleanField() is_offline = models.BooleanField() is_hidden = models.BooleanField() is_readonly = models.BooleanField() is_archive = models.BooleanField() is_system = models.BooleanField() is_temporary = models.BooleanField() class Meta: managed = False db_table = 'FileTable' unique_together = (('parent_path_locator', 'name'),) class DjangoMigrations(models.Model): app = models.CharField(max_length=255) name = models.CharField(max_length=255) applied = models.DateTimeField() class Meta: managed = False db_table = 'django_migrations' Filetable SQL info Filetable SQL info -
Django DRF: Make serializer field value equal to another one
I am creating an endpoint to reset the password and have created the serializer, views and I am using django.contrib.auth.forms to get the data and send email to the user. The form requires to type the new password two times but what I want is, to write it only once and make the value of new_password2 equal to new_password1. For example, I want to change the password on Swagger and it doesn't make sense to type it twice because it is a normal CharField and not a PasswordField. This is the serializers.py ResetPasswordConfirm class class ResetPasswordConfirmSerializer(serializers.Serializer): new_password1 = serializers.CharField(max_length=128) new_password2 = serializers.CharField(max_length=128) uid = serializers.CharField() token = serializers.CharField() set_password_form_class = SetPasswordForm def __init__(self, *args, **kwargs): super(ResetPasswordConfirmSerializer, self).__init__(*args, **kwargs) self.set_password_form = None def validate(self, value, *args, **kwargs): try: uid = force_text(uid_decoder(value['uid'])) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): raise ValidationError({ 'uid': ['Invalid value'] }) self.set_password_form = self.set_password_form_class(user=user, data=value) if not self.set_password_form.is_valid(): raise serializers.ValidationError(self.set_password_form.errors) if not default_token_generator.check_token(user, value['token']): raise ValidationError({ 'token': ['Invalid value'] }) return value def save(self, **kwargs): return self.set_password_form.save() And, the API View class ResetPasswordConfirmAPIView(GenericAPIView): serializer_class = ResetPasswordConfirmSerializer permission_classes = (AllowAny,) @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super(ResetPasswordConfirmAPIView, self).dispatch(*args, **kwargs) def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return …