Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
formset for OneToOne fields
I have three models in my Django app: class Parent (models.Model): pass class Sister(models.Model): pass class Brother(models.Model): owner = models.ForeignKey(to=Parent, on_delete=models.CASCADE) sibling = models.OneToOneField(to=Sister, on_delete=models.CASCADE) I need to let users choose for which Sister instances they want to create a corresponding Brother when I create a new Parent (Sisters as you can see are not connected to a Parent). The way I see it that when a user in a ParentCreateView I would also show them the list of all existing Sisters where they can put checkboxes in front of those for whom they would create a corresponding Brother. Then when they submit, a new Parent is created and corresponding number of Brothers attached to the sisters that have been chosen, and to a Parent that just has been created. I can't figure out though the right design: should I use inlineformsetfactory for that? Should I pass there existing sisters? Or I can just pass a checkbox field with existing sisters to a form where new Parent is created, and then create corresponding brothers in a post method of CreateView class. -
Serializing and Deserialzing User using Djoser Django Rest
I am quiet new to django and i am using djoser to create a user. I have custom user Model and Custom User Serializer. My Custom User is following. class User(AbstractBaseUser, PermissionsMixin): """ A fully featured User model with admin-compliant permissions that uses a full-length email field as the username. Email and password are required. Other fields are optional. """ email = models.EmailField(_('email address'), max_length=254, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) middle_name = models.CharField(_('middle name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) extra_field = models.BooleanField(_('changethis'), default=False, help_text=_('Describes whether the user is changethis ' 'site.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) username = models.CharField(_('username'), max_length=30, blank=True) roles = models.ManyToManyField(Role, related_name='role_user') objects = CustomUserManager() and following is my CustomUserManager() class CustomUserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, … -
Django rest. image url sends to html page but not to the image location
Have a picture upload in django rest app. The url is created and looks fine image related code is: Setting.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"),) MEDIA_URL = "/media/" MEDIA_ROOT = "uploads" URL from django.conf.urls.static import static from django.conf import settings if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) when click on the url the web browser shows nothing- just white(instead of picture). Inspected the page. It sends me not to the image but to the index.html file where I mounted my app: {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Combinator optimizer</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css2?family=Playfair+Display&display=swap" rel="stylesheet"> {% render_bundle 'app' %} -
Weird error with - python manage.py runserver (Exception in thread django-main-thread)
I am new to Python (to programming, generally), and I hit a brick wall: I am learning from Python Crash Course and I am cloning lessons. The third project in the book deals with Django. It says how you can create a website for keeping logs. I am creating, in parallel, another site, following the same exact instructions. I got through alright until I got to the point where, trying to run my own project, I cannot run the server with python manage.py runserver. when I run this for the original project, it works perfectly. When I stop the server (Ctrl+c) and run the command for my project, I get an error. before I edited certain files, .py files, that is, the command worked for my project, also. I didn't install or uninstall anything. I traced back and reversed every change I've made since the last time the command worked, but I couldn't get rid of the error. I am working with Python 3.8.3 IDE: PyCharm I have Django 3.0.7 I work in totally separated folders, I run everything in virtual environment (which I start using the command venv\Scripts\activate OS: Windows 10 Now, for the project where the runserver command … -
Django: queriying models not related with FK
I'm developping a Django project. I need to make many queries with the following pattern: I have two models, not related by a FK, but that can be related by some fields (not their PKs) I need to query the first model, and annotate it with results from the second model, joined by that field that is not de PK. I can do it with a Subquery and an OuterRef function. M2_queryset = M2.objects.filter(f1 = OuterRef('f2')) M1.objects.annotate(b_f3 = Subquery(M2_queryset.values('f3'))) But if I need to annotate two fields, I need to do this: M2_queryset = M2.objects.filter(f1 = OuterRef('f2')) M1.objects.annotate(b_f3 = Subquery(M2_queryset.values('f3'))).annotate(b_f4 = Subquery(M2_queryset.values('f4'))) It's very inneficient because of the two identical subqueries. It would be very interesting doing something like this: M2_queryset = M2.objects.filter(f1 = OuterRef('f2')) M1.objects.annotate(b_f3, b_f4 = Subquery(M2_queryset.values('f3','f4'))) or more interesting something like this and avoiding subqueries: M1.objects.join(M2 on M2.f1 = M1.f2)... -
Formulas for Optimizing Celery Configurations
I'm trying to figure out celery, and most of the configurations I've landed on have been from guesswork and monitoring jobs/performance after I update settings. A couple of interesting observations - I have continued to see a redis error ConnectionError('max number of clients reached',). It has happened when I have added more periodic tasks. The confusing part about this is my redis plan has a max of 40 connections. In my django app I configured celery to allow for 20 as the max amount of redis connections. Some of the configurations can be found below. CELERY_REDIS_MAX_CONNECTIONS = 20 CELERY_RESULT_EXTENDED = True CELERY_BROKER_TRANSPORT_OPTIONS = { "fanout_prefix": True, "fanout_patterns": True, "max_connections": 10, "socket_keepalive": True, } I finally upgraded Celery, Redis, and Celery Beat, and removed the above configurations. I have not seen the same issue since. celery-redbeat==0.13.0 --> celery-redbeat==1.0.0 celery==4.3.0 --> celery==4.4.4 redis==3.3.11 --> redis==3.5.3 So after this upgrade my connection errors have gone away for now. I notice in my redis instance that the number of connections has almost halved from a daily average of 39, to 24. The next error I tackle is r14 errors where I'm going over my memory limit. I fix this by setting --concurency=4 It was … -
Django makemessages “struct.error: unpack requires a buffer of 4 bytes”- python manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/vagrant/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/vagrant/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/vagrant/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/vagrant/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/vagrant/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/vagrant/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/vagrant/env/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/vagrant/env/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/vagrant/env/lib/python3.6/site-packages/django/contrib/auth/models.py", line 91, in <module> class Group(models.Model): File "/home/vagrant/env/lib/python3.6/site-packages/django/db/models/base.py", line 160, in __new__ new_class.add_to_class(obj_name, obj) File "/home/vagrant/env/lib/python3.6/site-packages/django/db/models/base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "/home/vagrant/env/lib/python3.6/site-packages/django/db/models/fields/related.py", line 1585, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) File "/home/vagrant/env/lib/python3.6/site-packages/django/db/models/fields/related.py", line 1066, in create_many_to_many_intermediary_model 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, File "/home/vagrant/env/lib/python3.6/site-packages/django/utils/functional.py", line 160, in __mod__ return str(self) % … -
Django Inlineformset not saving in class based updateview
I have a Book and Chapter model with one-to-many relationship. In my views.py I have two classes ChapterEdit and ChaptersManage, to update one Chapter and all Chapters respectively. I am using inlineformset for the ChaptersUpdate view to edit all the chapters that belong to a book. But when I update, the POST request doesn't do anything. The view is not saving the changes to the DB. I don't see any errors either. views.py class ChaptersManage(LoginRequiredMixin, UpdateView): login_url = reverse_lazy('login') model = Book fields = ["title", "order"] template_name_suffix = '-manage' #book-manage.html slug_field = 'slug' slug_url_kwarg = 'book_slug' def get_context_data(self, **kwargs): context = super(ChaptersManage, self).get_context_data(**kwargs) if self.request.POST: context['formset'] = ChapterFormSet(self.request.POST, instance=self.object) context['book'] = self.get_object() else: context['formset'] = ChapterFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super(ChaptersManage, self).form_valid(form) forms.py class ChapterEditForm(ChapterForm): def __init__(self, *args, **kwargs): super(ChapterEditForm, self).__init__(*args, **kwargs) class Meta(ChapterForm.Meta): fields = ChapterForm.Meta.fields ChapterFormSet = inlineformset_factory( Book, Chapter, form=ChapterEditForm, fields=('title', 'order'), extra=0) What am I missing? -
Django login form not loggin in user with Vuetify
I am new to web development. I am unable to login using django login view after I use vuetify text-field however there is no problem when I don't use Vuetify. Here is the code: Base template <html> <head> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui"> </head> <body> <div id="app"> <v-app> <v-content> <v-container>{% block forms %}{% endblock forms %}</v-container> </v-content> </v-app> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script> <script> new Vue({ el: '#app', vuetify: new Vuetify(), }) </script> </body> </html>``` Template {```% extends 'LoginAndSignUp/BaseAuthenticationPage.html' %} {% block forms %} <form action="" method="post"> {%csrf_token%} <v-text-field label='Username'> {{form.username}} </v-text-field> <v-text-field label='Password'> {{form.password}} </v-text-field> <v-btn type='submit'>Login</v-bt> </form> {% endblock forms %}``` -
Django : How to get all data related to logged in user
I want to create a view that returns all data from a model related to the currently logged-in user. eg i have a model that has a relationa to the User table set belo in user_rel : from django.db import models from django.contrib.auth.models import User class ProcessInfo(models.Model): date_created = models.DateTimeField(auto_now_add=True, null=True) user_rel = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) tags = models.ManyToManyField(Tag) I want to write a view and this is what I have : def processList(request): user_pk = request.user.id processess = ProcessInfo.objects.get(user_rel=user_pk) context ={ 'processess':processess, } return render(request, 'process/process_list.html', context) I am expecting a list of all processes inserted by the currently logged in user. How do I fix this vew? -
Using multiple dropzones in one form and sending data to django which takes only one request
First I am a beginner in dropzone and javascript. I have one html form, 3 instances of dropzone and the view.py. I want to send with each instance of dropzone different types -> Pictures, documents and videos. There are also data like char and int which I packed in the picture instance by using formData.append. So far I am able to get data from the first instance (picture) by using mydropzone.processQueue() when I fire the submit button on my form. How do I get the other files from the other dropzones into that request? Here the html part: <form id="postform" action="" method="POST" enctype="multipart/form-data" > {% csrf_token %} {{ form.media }} {% include 'Admin/includes/customformfield.html' %} <div id="dropzoneBild" class="dropzone"></div> <div id="dropzoneVideo" class="dropzone"></div> <div id="dropzonePdf" class="dropzone"></div> <div class="row-6"> <button class="btn btn-primary btn-round" type="submit" name="Submit">Submit</button> </div> </form> Here the dropzone instance for picture. The other two dropzones are the same except that the paramName is different and there is no formData.append for the char and int, also the acceptedFiles is different: (function () { var postform = document.getElementById('postform'); Dropzone.autoDiscover = false; var myDropzonebilder = new Dropzone("div#dropzoneBild", { url: postform.action, paramName: "filebilder", autoProcessQueue: false, uploadMultiple: true, parallelUploads: 50, maxFiles: 50, addRemoveLinks: true, acceptedFiles: ".jpeg,.jpg,.png", init: … -
Django import export display all of the values in foreignkey into csv
This is a random model i created to show what im looking for. In this model the store email field is a foriegn key taken from another model which is already populated. There are 10 values in the store email field and i want the exported csv to show all 10. But currently it shows the selected in the picture. -
TemplateDoesNotExist at /admin/listofposts/post/add/
I am trying to install quill-editor but it gives the TemplateDoesNotExist error when I am trying to open it from django admin panel Error during template rendering In template /home/tanmoy/.local/lib/python3.6/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 {% for field in line %} 10 <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 {% if field.is_checkbox %} 13 {{ field.field }}{{ field.label_tag }} 14 {% else %} 15 {{ field.label_tag }} 16 {% if field.is_readonly %} 17 <div class="readonly">{{ field.contents }}</div> 18 {% else %} 19 {{ field.field }} 20 {% endif %} 21 {% endif %} 22 {% if field.field.help_text %} 23 <div class="help">{{ field.field.help_text|safe }}</div> 24 {% endif %} 25 </div> 26 {% endfor %} 27 </div> 28 {% endfor %} 29 </fieldset> -
Django: BaseEmailMessage send BCC emails
When I send emails using BaseEmailMessage, the recipients see each other. I want to avoid this. I tried to use be bcc instead of the to parameter: class ExampleEmail(BaseEmailMessage): pass ExampleEmail(context=context).send(bcc=['example@example.com']) I get an error that the to parameter is required. How can I send emails without recipients being aware of each other? -
what is django most used for
so i know django is a frame work. But I wanted to know what it was most use for. In this post I am linking the most upvote comment. Said it is known/famous/use for Django admin.But I want to know what else it is use for before I try to learn/use it. Also is it useful for database web stuff if so what do people usually use it for in database web stuff? Thanks in advance sorry if this is a really amateur question Is Django for the frontend or backend?. -
How to validate fields properly in Graphene Django
I'm using django-phonenumber-field and graphene-django. Could you tell me how to let graphql throw an error when I'm creating an user with incorrect telephone number format? And also I would like to know how to test it. -
Change Django Celery beat interval
I'm newbie with Django Celery, I ran this command: celery -A projectname beat -l info It print that maxinterval -> 5.00 minutes (300s) I want to extend it to 10 minutes, how can I do it ? -
making a battle royle result sheet. (django)
I have made a model class Results. It stores 'position' of a team and 'kills' secured by team during a tournament. The model class is as follows:- class Results(models.Model): teams=models.ForeignKey(Teams,null=True,on_delete=models.CASCADE) position= models.IntegerField(blank=True,null=True) kills=models.IntegerField(blank=True,null=True) matches=models.ForeignKey(Matches,null=True,on_delete=models.CASCADE) placement_point=models.IntegerField(null=True,default=0) kill_points=models.IntegerField(null=True,default=0) total_points=models.IntegerField(null=True,default=0) now, the team which get 1st postion gets 10 placement points, 2nd get 8, 3rd get 6, 4th get 5, 5th get 4 and all other teams get 0 placement points. Also each kill give 1 kill points(ex 15 kill-> 15 points). This position vs position points is also stored in table class PointsTable(models.Model): position=models.IntegerField(null=True) placement_point=models.IntegerField(null=True) kill_points=models.IntegerField(null=True,default=1) here teams represent individual team like fnatic, cloud9 etc. You can ignore matches field in Results class. All i want to automatically calculate and fill total_points, placement_point, kill_points. Example :- if fnatic get 2nd position with 15 kill then placement_point=8, kill_points=15*1,total_points=8+15=23. actually i m trying to solve this problem using django signal. But i m stuck.Kindly help me out, Thanks. -
Auto model creation through relationship Django
I got a model class Incarico(models.Model): polizza = models.OneToOneField(Polizza, default=None, blank=True, on_delete=models.CASCADE, null=True) and this model here class Polizza(models.Model): partite = models.CharField(max_length=50, default=None, blank=True, null=True) i need to create First the Incarico model through a form compiled by some users, at the moment of creation of Incarico, Polizza needs to be created and linked with the same id. How could i manage to do this? Any help is appreciated!!! -
Requested setting INSTALLED_APPS, but settings are not configured
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. from proto.department import DepartmentSummary courseA = course.objects.values_list('No_Students', flat=True) courseA = list(courseA) department_name=['BSCS'] count = 0 total_students = 0 length = len(courseA) i=0 while i<length: if courseA>0: count=count+1 total_students = total_students+courseA for name in department_name: lt, created = DepartmentSummary.objects.get_or_create( Department_Name=name, ) if not created: lt.Active_courses = count lt.Active_students = total_students lt.save() ``` *i'm trying to fetch data from a model and perform calculations on it and then uploading it into another model but it's showing me this error can anyone tell what to do.* -
Unable to view Product Page - Python django
Im new to python and django and working on a ecommerce project but facing some issues with product details page. Below are the codes for your reference. pls help out what im doing wrong here. Im trying to get product.product_name but its giving error no attribute view: def product_page(request, myid): print(myid) product = Lat_Product.objects.filter(id=myid) print(product) return render(request, 'product_page.html', {'product': product}) url urlpatterns = [ path('', views.lat_product, name="home"), path('product_page/<int:myid>', views.product_page, name='product page') ] model class Lat_Product(models.Model): objects = models.Manager() product_name = models.CharField(max_length=100) product_price = models.IntegerField() product_desc = models.CharField(max_length=150) product_disc = models.BooleanField() product_image = models.ImageField(upload_to='pics') product_new = models.BooleanField() result Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. 1 <QuerySet [<Lat_Product: Lat_Product object (1)>]> [08/Jun/2020 17:21:37] "GET /product_page/1 HTTP/1.1" 200 17009 Not Found: /product_page/site.webmanifest [08/Jun/2020 17:21:37] "GET /product_page/site.webmanifest HTTP/1.1" 404 3017 -
Django: how to dynamically generate pdf of the state of current page and email automatically?
I would like to send whatever is in the current page (either as html or as pdf), as an email upon click of a link. Is there a way to do this in DJango? -
Django Url Content Redirect working on Windows but Ubuntu
When i test on windows it's working properly but on uwsgi/nginx Ubuntu it always display previous variables on redirect page. Thank you for your help. My code is basically user enter some variables on home page then i redirect it to the second page to see each time if it has been updated. def create(request): global subnet global vlan_Name if request.method=="POST": vlan_Name=request.POST.get("vlan", "") subnet=request.POST.get("Subnet", "") def nexus(request): context={ 'subnet':subnet, 'vlan_name': vlan_Name, 'vlan_id': VLAN_ID, 'hsrp1':hsrp1, 'hsrp2':hsrp2, 'hsrp_array':hsrp_array, 'gateway':gateway, 'FW_IP':FW_IP, } return render(request,'nexus.html',context) HTML FILE: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> </title> </head> <body style="background-color:LIGHTGREEN;"> <p>name {{vlan_name}} <p> <p>mysubnet {{subnet}} <p> <form action = "/submit" method="post"> {% csrf_token %} <input type="submit" value="Send" style="font-family:verdana;" > </form> </body> </html> -
Why is my Django form returning the QueryDict without the submitted data?
The issue I'm having is that my form data returns not None nor the form values I entered, but simply just the usual csrf_token string and the button's value. I verified this by printing Form(response.POST).data, which returns a QueryDict with just the csrf_token value and the value of the submit button: <QueryDict: {'csrfmiddlewaretoken': ['the token string'], 'save_customer': ['save_customer']}> Contrast this with the other working form's output that works. (I happen to be executing both procedures nearly identically): <QueryDict: {'tail': ['aasdf'], 'aircraft': ['asdf'], ...it's all here... 'csrfmiddlewaretoken': ['the token string'], 'add': ['add']}> So basically, my HTML file includes 2 forms. One form works, and the other doesn't. Having more than one form shouldn't be an issue, especially considering one form is in it's own separate container, and the other form resides in a modal. They do not share any "divs" with each other, nor any "parenting". However, it should be noted that the 2nd form's corresponding view is automatically executed on page load and without any prior doing. The simple existence of the second form causes this to happen. I've deleted the javascript files, removed all traces of javascript functionality within the second form, and yet the view still gets called … -
Auth system checks superuser instead of custom user moel?
I created a custom authentication model. I am trying to authenticate custom user model but instead of that it checks for superusers(users that are created on python shell). Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name='email address',max_length=255,unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) username =models.CharField(max_length=80,unique=True) Views.py class UserLoginView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) response = { 'message': 'User logged in successfully', 'token' : serializer.data['token'], } status_code = status.HTTP_200_OK return Response(response, status=status_code) def get(self, request, format=None): queryset = User.objects.all() serializer = UserRegistrationSerializer() return Response(serializer.data) Serializers.py class UserLoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): email = data.get("email", None) password = data.get("password", None) user = authenticate(email=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password is not found.' ) try: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) update_last_login(None, user) except User.DoesNotExist: raise serializers.ValidationError( 'User with given email and password does not exists' ) return { 'email':user.email, 'token': jwt_token } Basically i am trying to authenticate my custom created users (created from my custom registration form instead of user).Can somebody help?