Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to optimize loading millions of records in MongoDB with Django admin?
I have MongoDB with over 20 million records integrated with Django administration. Both services are running in k8s. I have already applied some of the optimisations below: Adding NoCountPaginator (disable counting) Indexing MongoDB Sorting queryset Also, I read about adding skip and limit is not recommended since it will make the performance even worse. But still, loading is extremely slow and frequently throws timeout errors. Here's the custom manager to get queryset: models.py class RuleDataManagerRemoved(DjongoManager): def get_queryset(self): event_horizon = datetime.datetime.now() - datetime.timedelta(days=180) return RuleDataQuerySet(model=self.model, using=self._db, hints=self._hints).filter(last_change__gte=event_horizon) The filtering happens with indexed field, so I think the impact is not critical here. admin.py @admin.register(models.ChangedProductSlugs) class ChangedProductSlugsAdmin(RuleDataAdmin): paginator = NoCountPaginator show_full_result_count = False list_display = ('old_category_slug', 'old_product_slug', 'new_category_slug', 'new_product_slug', 'tld', 'last_change', 'created_by', 'stav') list_filter = ('last_change', ('old_product_slug', SingleTextInputFilterOldProduct), ('old_category_slug', SingleTextInputFilterOldCategory), ('new_product_slug', SingleTextInputFilterNewProduct), ('new_category_slug', SingleTextInputFilterNewCategory), 'deleted', 'deleted_by', 'tld') search_fields = ('old_category_slug', 'old_product_slug', 'new_category_slug', 'new_product_slug') resource_class = resources.ChangedProductSlugsResource actions = ['restore_queryset'] def stav(self, obj): return not obj.deleted stav.boolean = True def changelist_view(self, request, extra_context=None): default_filter = False try: ref = request.META['HTTP_REFERER'] pinfo = request.META['PATH_INFO'] qstr = ref.split(pinfo) if len(qstr) < 2: default_filter = True except: default_filter = True if default_filter: q = request.GET.copy() q['deleted__exact'] = '0' request.GET = q request.META['QUERY_STRING'] = request.GET.urlencode() return super(ChangedProductSlugsAdmin, … -
Django HttpRequest type hint / annotation problem
def my_func(request: HttpRequest) -> str: return request.user.email gives me a warning in PyCharm, saying that user is not a defined attribute. However writing it as request: HttpRequest() removes this warning, and gives me proper parameters in suggestions. Could someone explain why this is happening, and if I did something wrong? I'm importing HttpRequest from django.http. -
Django | I want to show the page to 'AnonymousUser' even though I'm using request.user in views.py
I want to show the page to all users even if they are not logged in but because im using request.user in views.py this is not possible. Is there anyway to handle this? views.py: class ServerView(View): def get(self, request, server_tag): server = Server.objects.get(tag=server_tag) posts = server.posts.all() is_following = False relation = ServerFollow.objects.filter(server=server, user=request.user) if relation.exists(): is_following = True return render(request, 'servers/server.html', {'server':server, 'posts':posts, 'is_following':is_following}) -
GA4 accounts not listed in Python
I want to list GA4 accounts in Python. But first, the user needs to connect Google Analytics account. Then I want to list the accounts with google.analytics.admin. How should I go about this? I followed this document but it didn't work: https://developers.google.com/analytics/devguides/config/admin/v1/quickstart-client-libraries#step_1_enable_the_api -
Django more type of user - ask about advice
I work on my project and i want create 3 type of user include Admin(user and second user with different premission). I want ask which method i should use to do it ? I read a bit about AbstractUser, create group and "flag's" 1th user - will can only add comment/ save file 2th user - will can create model and what 1th have 3th user - admin Admin after 2th get created should get notification that 2th suer get created and he need to accept his perrmision first (before he can create models like email and admin can do it in admin panel i think) -
Django DetailView count increases by 3 instead of 1
I have a webpage where every view is being counted by and incremented by 3 where it is intended to be incremented by 1 instead here's what I have in my views.py from django.views.generic import ListView, DetailView class MovieDetail(DetailView): model = Movie def get_object(self): object = super(MovieDetail, self).get_object() object.views_count += 1 object.save() return object def get_context_data(self, **kwargs): context = super(MovieDetail, self).get_context_data(**kwargs) context['links'] = MovieLink.objects.filter(movie=self.get_object()) context['related_movies'] = Movie.objects.filter(category=self.get_object().category) return context html <section class="movie"> <img src="{{object.image.url}}"> <ul> <li>{{object}}</li> <li>{{object.description}}</li> <li><a href="genre.html">Adventure</a>, <a href="genre.html">Drama</a>, <a href="genre.html">Romance</a></li> <li><a href="">{{object.cast}}</a></li> <li><i class="fa fa-eye" id="eye"></i> {{object.views_count}}</li> </ul> </section> It is scripted to increment by 1 but does not follow that logic.. what went wrong here? -
AttributeError at /class/55910/ 'tuple' object has no attribute 'get'
I've check the return render(), etc, I've all solutions and nothing happened. Thanks for solution, if you can solve this :) There is my classpage_views.py from django.shortcuts import render from django.http import HttpResponse from numpy import append from .models import Classes def class_article_preview(request, URLcodenumber): codenumber = Classes.objects.get(codenumber=URLcodenumber) schoolNum = '' classNum = '' def div_by_s_and_c(num): preSortArray = [] classSimLen = 1 if codenumber.is_2num_class == False: classSimLen = 1 else: classSimLen = 2 for sim in num: preSortArray.append(sim) schoolNumLen = len(codenumber.codenumber) - classSimLen for sim in preSortArray: nonlocal schoolNum schoolNum = schoolNum + str(sim) schoolNumLen = schoolNumLen - 1 if schoolNumLen <= 0: break for sim in reversed(preSortArray): nonlocal classNum classNum = classNum + sim classSimLen = classSimLen - 1 if classSimLen <= 0: classNum = classNum[::-1] break return classNum, schoolNum div_by_s_and_c(codenumber.codenumber) return classNum, schoolNum context = {'clsName': f'Школа №{schoolNum}, \n{classNum} параллель', 'articles': ['test', 'test2']} return render(request, 'blogpage\\articles_preview.html', context) def class_article_create(request): return render(request, 'blogpage\\create_article.html') This is traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/class/55910/ Django Version: 4.0.3 Python Version: 3.10.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'start_page', 'help_page', 'class_page'] Installed 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'] Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner … -
What Django model field to use for the following JSON data from draft.js (react-draft-wysiwyg)?
I have a react-draft-wysiwyg component in my NextJS app, and I am trying to find a way to store that to my Django REST backend. This is the stringified JSON I get directly from the draft component, but I am not sure how to organize the django model to store such data as well as be able to make PATCH and GET requests later. Would appreciate any help! { blocks: [ { key: '64o0i', text: 'Introduction edited', type: 'header-three', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, { key: 'dcomv', text: 'this will be the awesome shit', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, { key: 'edvnc', text: 'Body paragraph', type: 'header-three', depth: 0, inlineStyleRanges: [ { offset: 0, length: 14, style: 'color-rgb(0,0,0)' }, { offset: 0, length: 14, style: 'bgcolor-rgb(255,255,255)' }, { offset: 0, length: 14, style: 'fontsize-24' }, { offset: 0, length: 14, style: 'fontfamily-ui-sans-serif, system-ui, -apple-system, "system-ui", "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji', }, ], entityRanges: [], data: {}, }, { key: 'd3sf7', text: 'this will be the awesome shit klasdfj lk;', type: 'unstyled', depth: 0, inlineStyleRanges: … -
Can't get data when writing interface using djangorestframework
from django.http import JsonResponse, Http404 from django.views import View from rest_framework.generics import GenericAPIView from rest_framework import filters from rest_framework.response import Response from persons.models import Persons from persons.serializer import PersonModelSerializer import json class PersonList(GenericAPIView): filter_backends = [filters.OrderingFilter] ordering_fields = ['name','nickname','grangs'] queryset = Persons.objects.all() serializer_class = PersonModelSerializer def get(self,request): person_qs = self.queryset person_qs = self.filter_queryset(person_qs) serializer = self.get_serializer(instance=person_qs,many=True) return Response(serializer.data) 编写一个查询接口报错提示: 'Do not evaluate the .queryset attribute directly, ' RuntimeError: Do not evaluate the .queryset attribute directly, as the result will be cached and reused between requests. Use .all() or call .get_queryset() instead.enter image description here -
Using a custom language gives "You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting."
I've just upgraded my Django project from 2.2 to 3.2 and the language broke. I had this piece of code which was working fine (inside my settings.py) LANGUAGE_CODE = 'tb' EXTRA_LANG_INFO = { 'tb': { 'bidi': False, 'code': 'tb', 'name': 'English', 'name_local': 'United States', 'fallback': ['en-US'], }, } import django.conf.locale LANG_INFO = dict(**django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO Now I get ?: (translation.E004) You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting. Why is this happening and how can I fix it? Thanks. -
Static dict definition is python application till application is running
Trying to implement the the java static map implementation in python application. Tried approach: created a global dict, and trying to access it and update the same but not working. Created a class and created a global variable and trying to set and fetch from there. class staticdict: dict={} def init(self,type,data): self.dict[type]=data def __getitem__(self,type): return self.dict[type] setting the values : staticdict(type,nseTemp) fetching the values : print(" data----- "+ staticdict.getitem(type)) Error : TypeError: staticdict.getitem() missing 1 required positional argument: 'type' Also not sure this approach will work or it will keep on creating the new instance of class and override the dict present in the class. I want to keep the dict which will hold the data for static map -
How to use _set in SerializerMethod for instance?
I want to calculate the average rating by using SerializerMethodField(). The error in the following code is AttributeError: 'FeedbackModel' object has no attribute 'aggregate' I think _set is missing but I don't know where to put it..! class FeedbackSerializer(serializers.ModelSerializer): feedback_by_user_profile_pic = serializers.ImageField(source='feedback_by.profile_pic') average_rating = serializers.SerializerMethodField() def get_average_rating(self,instance): return instance.aggregate(average_rating=Avg('rating'))['average_rating'] class Meta: model = FeedbackModel fields = ['feedback_text','rating','date','feedback_by_user_profile_pic','average_rating'] Feedback Model class FeedbackModel(models.Model): feedback_text = models.CharField(max_length=1000) rating = models.IntegerField() date = models.DateField(auto_now=True) feedback_by = models.ForeignKey(UserModel,on_delete=models.CASCADE) business_account = models.ForeignKey(BusinessAccountModel,on_delete=models.CASCADE) class Meta: db_table = 'feedback' -
Django REST Serializer permanently changed in init
I'm facing a weird issue with DRF: I have several serializers for which I want to display certain fields only under specific conditions, such as url parameters there being in the request or the user having certain permissions. To decouple my serializer's presentation logic from the business logic, I decided to add a conditional_fields attribute to the serializer's Meta class: it's a dict in which the keys are strings representing conditions, such as "SHOW_HIDDEN_FIELDS" and their values are lists of field names that need to be removed if the key isn't present in the serializer context. Then I override my viewsets' get_serializer_context method to get the desired values inside of context. I made a remove_unsatisfied_condition_fields method which does the following: def remove_unsatisfied_condition_fields(self): conditional_fields = self.Meta.conditional_fields for condition, fields in conditional_fields.items(): if not self.context.get(condition, False): for field in fields: self.fields.pop(field, None) The serializers making use of it look like this: class ExerciseSerializer(serializers.ModelSerializer): class Meta: model = Exercise fields = [ "id", "text", "solution", "correct_choices" ] conditional_fields = { "EXERCISE_SHOW_HIDDEN_FIELDS": ["solution", "correct_choices"], } Here comes the problem: if I manually call this method inside my serializers, in their __init__ method, like this: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.remove_unsatisfied_condition_fields() everything works fine. … -
The css in extended html file(child file) is not working in django
I have created two html pages and a CSS file in static directory This is my main.html {% load static %} <html> <head> <title> </title> <link rel ="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <nav> <ul> <li><img src="{% static 'images/logo.jpg'%}" height="49px" width="100px" > <li><a href=#> HOME</a></li> <li><a href=#> ABOUT</a></li> <li><a href="rent"> RENT</a></li> <li><a href="sale"> SALES</a></li> </ul> </nav> {% block content %} {% endblock %} </body> <hr> <footer> The CSS in main.html is working, This is my index.html {% extends 'main.html' %} {% block content %} <div id="showcase"> <div class="section-main container" > <h1>House rent & Sale</h1> <p class="lead hide-on-small">This is a web application </p> </div> </div> {% endblock%} The CSS in index.html is networking. How can I solve this ? Please help me -
Django Model advance Foreignkey Relation
I have a Django model which has relationship with user model. Where user are assigned to groups. especially "Admin", "Teacher","Student". So I want to make a foreign key relationship in such a way that it will show only The users that have been assigned to Teacher groups for Teacher_details model, And Similar for Student_Details Model. I have made the models Teacher_Details , Student_Details and established foreign key relation with User model. But the problem is that its showing all the user when I am filling Student_Details or Teacher_Details. Hope you got my problem. I am hoping positive response. The code looks like this: class Student_Details(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='none', upload_to='img/') details_updated = models.DateTimeField(auto_now_add=True) address = models.CharField(max_length=150) admission_date = models.DateField() previous_college = models.CharField(max_length=150) course_enrolled = models.ForeignKey(ModelUniversity,on_delete=models.CASCADE) semester = models.CharField(max_length=20,choices=semester,default=None) def __str__(self): return self.user.first_name class Teacher_Details(models.Model): address = models.CharField(max_length=150) image = models.ImageField(default='none', upload_to='img/') details_updated = models.DateTimeField(auto_now_add=True) subject_taught = models.ManyToManyField(to='Student.stu_subject') user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return self.user.first_name def subject_teacher_teaches(self): return [str(s) for s in self.subject_taught.all()] -
Django ForeignKey self conditions
I have the model, where each Character has 'mother' and 'father' fields. They are FroeignKey which refers to self. I want to put condition for the gender, 'F', 'Female' for the mother field and 'H', 'Male' for the father field. class Character(models.Model): H = 'Male' F = 'Female' GENDER_CHOICES = ( (H, 'Male'), (F, 'Female'), ) last_name = models.fields.CharField(max_length=100) first_name = models.fields.CharField(max_length=100) gender = models.CharField(max_length=30, choices=GENDER_CHOICES, null=True, blank=True) mother = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='linkmother') father = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='linkfather') date_birth = models.DateField(default=date.today, null=True, blank=True) date_death = models.DateField(default=date.today, null=True, blank=True) def __str__(self): return f'{self.first_name} {self.last_name}' -
Django - implement nested loop in ajax function
I have a Django app (3.2) and I am trying to implement filters in Ajax in jquery that will filter all products based on selected filters. The problem is that Ajax is filtering only areas, not needs and products. How can I implement a nested loop in Ajax so it will work in the same way as my product_list and I will see not the whole area but only relevant products? views.py def filter_data(request): client_type = request.GET.getlist('client_type[]') business_challange = request.GET.getlist('business_challange[]') product_list = Area.objects.prefetch_related(Prefetch("need_area", queryset=Need.objects.filter(category_need__product__isnull=False,category_need__product__status=1).distinct())).filter(need_area__category_need__product__isnull=False, need_area__category_need__product__status=1).distinct() if len(client_type) > 0: product_list = product_list.filter(need_area__category_need__product__client_type__title__in=client_type).distinct() if len(business_challange) > 0: product_list = product_list.filter(need_area__category_need__product__business_challange__title__in=business_challange).distinct() context = { 'areas': product_list, } ajax_template = render_to_string('product-list-ajax.html', context) return JsonResponse({'data': ajax_template}) product-list-ajax.html {% for area in areas %} <div class="border mb-4 pb-4 px-2"> <h2 class="fw-bold my-2">{{area.title}}</h2> {% for need in area.need_area.all %} <h4 class="text-muted mt-4">{{need.title}}:</h4> {% for product_category in need.category_need.all %} {% for product in product_category.product.all %} <a href="{{product.get_absolute_url}}" class="pe-2"><span>{{product.title}}</span></a> {% endfor %} {% endfor %} {% endfor %} </div> {% endfor %} product-filters.js $(document).ready(function(){ $(".ajaxLoader").hide(); $(".form-check-input").on('click', function(){ var filterObj={}; $(".form-check-input").each(function(index,ele){ var filterVal=$(this).val(); var filterKey=$(this).data('filter'); filterObj[filterKey]=Array.from(document.querySelectorAll('input[data-filter='+filterKey+']:checked')).map(function(el){ return el.value; }); }); //Ajax $.ajax({ url: 'filter-data', data: filterObj, dataType: 'json', beofreSend: function(){ $(".ajaxLoader").show(); }, success: function(res){ $("#filteredProducts").html(res.data); $(".ajaxLoader").hide(); console.log(res) } }); … -
Python strptime for empty string or None value from database
Getting values from a database table and when the field is empty string or None its giving me this error: time data '' does not match format '%Y-%m-%d %H:%M:%S.%f' first_date = users.work.values_list('work_date', flat=True) a = datetime.datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S.%f') b = a.strftime("%m/%d/%Y") Output: 2022-06-02 11:16:41.012000+00:00 But the output also will be null in table How I can skip this '' or None values, without try except and other huge lines of code, please advice Thanks. -
Count and store Number of logins in Django
I am new to Django framework. I am trying to record number of logins by a particular user(s) and display it in my Django panel. I went through the discussion here https://stackoverflow.com/questions/2526966/count-number-of-logins-by-specific-user-django But could not understand which code is to put in which file i mean what to put in models.py and signals.py or otherwise. Please help. -
Django admin page not work properly and show weird look
Today I have updated Django to the latest version. But for some reason when the logged in to the admin page, all I cans see is a weird-looking admin page. enter image description here how to solve this problem? -
Django form won't submit but not showing error
models.py class HopperFillData(models.Model): no_mesin = models.CharField('No Mesin', max_length=3, choices=mesin_choice, default=mesin_choice[0]) product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Product', default=None) no_lot = models.IntegerField('No Lot', blank=True, null=True) temp = models.IntegerField('Temperature', blank=False, null=False) tanggal = models.DateField('Tanggal', blank=False, null=False) jam_isi = models.TimeField('Jam Isi', blank=False, null=False) target_pemakaian = models.PositiveIntegerField('Usage Total', blank=False, null=False) pemakaian_virgin = models.PositiveIntegerField('Usage Virgin', blank=False, null=False) pemakaian_regrind = models.PositiveIntegerField('Usage Regrind', blank=False, null=False) pic = models.ForeignKey(UserModel, on_delete=models.CASCADE, verbose_name='PIC', to_field='username', blank=True, null=True) shift = models.CharField('Shift', max_length=7) def __str__(self): hop = '{0.no_mesin}' return hop.format(self) def get_absolute_url(self): return reverse('hopper_fill_data') forms.py class HopperFillForm(ModelForm): def __init__(self, *args, **kwargs): super(HopperFillForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.layout = Layout( Row( Column('no_mesin', css_class = 'col-md-2'), Column('product', css_class = 'col-md-7'), Column('no_lot', css_class = 'col-md-1'), Column(AppendedText('temp', '°C'), css_class = 'col-md-2'), css_class = 'row' ), Row( Column(MultiWidgetField('tanggal', attrs = ({'style':'width : 30%; display: inline-block; margin-right:0.15em'},)), css_class='col-md-8'), Column('jam_isi', css_class = 'col-md-4'), css_class = 'row' ), Row( Column(AppendedText('target_pemakaian', 'kg'), css_class = 'col-md-4'), Column(AppendedText('pemakaian_virgin', 'kg'), css_class = 'col-md-4'), Column(AppendedText('pemakaian_regrind', 'kg'), css_class = 'col-md-4'), css_class = 'row' ), Submit('submit', 'Submit Material Hopper') ) self.fields['tanggal'].widget = SelectDateWidget(years = range(2000, date.today().year+3)) self.fields['tanggal'].initial = datetime.today() self.fields['jam_isi'].widget = forms.TimeInput(attrs={'type':'time'}) self.fields['jam_isi'].input_formats = settings.TIME_FORMAT self.fields['jam_isi'].initial = datetime.today().strftime('%H:%M') self.fields['shift'].widget = forms.HiddenInput() self.fields['shift'].initial = 'Shift 1' self.fields['pic'].widget = forms.HiddenInput() self.fields['pic'].initial = None class Meta: model = HopperFillData … -
How to get drop down formdata in console by ajax call
I've a form which contains input text fields and drop down.When I pass data using ajax call.All data printing in the console except drop down selected data.It shows undefined? How to inspect selected form data? -
Block Thread execution until completed in test Python Django
I have a Django app that needs to make some 3d service call to compute embedding. This call takes time and blocking execution and I want to make it async. For this I am using Thread. class MyView(): def create_answer_embedding(answer): embedding = long_computing_call(answer) db.write(embedding) <- pseudo code, the idea is that after creating the embedding, we create an AnswerEmbedding obj. in the db def post(request, *args, **kwargs): answer = request.data.get("answer") Thread(target=self.create_answer_embedding, args=(answer, )).start() return Response() So the thread starts calculating embedding and the view returns a response. Once calculating is finished, a new AnswerEmbedding object is created in the DB. Now I need to test it works properly. So if I just run a test that makes an api call: response = client.post("/my-view") answer_embedding = AnswerEmbedding.objects.get(answer__id=response.json()['id']) This test fails because it checks AnswerEmbedding.objects.get before it is actually created in the Thread. So, I need to somehow either make this Thread running sync or find a way to properly mock it. I could just mock the Thread but with this the test will not check if the embedding is created or not. Any ideas? Thanks -
How can I upload files asynchronously in Django? Can I use Celery for this purpose? I passed django form to the task and it didn't work
Normally, we can deploy celery for async. Can celery be used for asynchronous file uploading, which allows client to continue working on the website while big size of file being uploaded? I passed the forms to the task of the celery and I had an error like 'Object of type module is not JSON serializable'. Is there any way for async file uploading? -
Python Django {'user': [ErrorDetail(string='Incorrect type. Expected pk value, received BoundField.', code='incorrect_type')]}
I'm developing my backend on Django. I wrote a code for user registration under RegistrationView class, and it worked fine before. I had to incorporate email confirmation in it, which also worked fine on its own. However, after all of that was done, I added some conditions to ensure proper working, but I get the "string='Incorrect type. Expected pk value, received BoundField.'" and "Forbidden: /api/v1.0/user/register-patient/" error. Also, to clarify the workflow. Each user is assigned a JWT token while signing up. This token is different from the token sent to verify email. I named the latter "verification_token". So a user signs up, their 'is_active' field is set to False until they click on the link received in their email. Sendgrid email API was used to send the email. The email is only sent if the patient_serializer data is stored in the db. When the user clicks on the link received through email, their 'is_active' field is set to True, and they can now log in. Also, the actual sendgrid API key is a part of the code, I removed it here. My models.py file: from django.db import models from django.contrib.auth.models import User class VerificatonToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') …