Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the date format in the model history section in the Django admin panel from Gregorian to Jalali?
I changed the date and time of the admin panel using the Jalali-date package, and now if I go to the special page for each model in the admin panel It shows the date of manufacture in Jalali format. But if I go to the history section of that model, I see that the dates are displayed normally in the Django system. Note: Jalali Library transforms the world standard history into the conventional history in Islamic countries the package i have used: text my models: from django.db import models from django.contrib.auth.models import User from django_jalali.db import models as jmodels class Thought(models.Model): title = models.CharField(max_length=150, verbose_name = 'عنوان تسک') content = models.CharField(max_length=400, verbose_name = 'متن') date_posted = jmodels.jDateTimeField(auto_now_add=True, verbose_name='تاریخ') user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True, verbose_name = 'کاربر') class Meta: verbose_name = 'تسک' verbose_name_plural = 'تسک ها' def __str__(self): return self.title class Profile(models.Model): profile_pic = models.ImageField(null=True, blank=True, default='Default.png', verbose_name = 'عکس پروفایل') user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, verbose_name = 'کاربر') class Meta: verbose_name = 'پروفایل' verbose_name_plural = 'پروفایل ها' def __str__(self): return self.user.username my admin file: from django.contrib import admin from .models import Thought, Profile from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from jalali_date import datetime2jalali from jalali_date.admin import ModelAdminJalaliMixin … -
plain text instead of HTML element in Django
I have a model like this: class FirstOne(models.Model): title = models.CharField(max_length=250) pretext = models.TextField(null=True, blank=True, default=None) first = models.PositiveIntegerField() last = models.PositiveIntegerField() and then another model is like this: class SecondOne(models.Model): def first_one_pretext(self): pk = self.firstone.pk a = FirstOne.objects.filter(pk=pk).get() return a.pretext And when I do this, I always get a "html element" and not the plain text stored in pretext of the object. How do I get rid of this? -
Embedding a document into chromadb using langchain
Im trying to embed a pdf document into a chromadb vector database using langchain in django. I want to do this using a PersistentClient but i'm experiencing that Chroma doesn't seem to save my documents. from rest_framework.response import Response from rest_framework import viewsets from langchain.chat_models import ChatOpenAI import chromadb from ..functions.load_new_pdf import load_new_pdf from ..functions.store_docs_vector import store_embeds import sys from ..models import Documents from .BaseView import get_user, strip_user_email from ..functions.llm import chosen_llm from langchain_community.vectorstores import Chroma from langchain.embeddings.openai import OpenAIEmbeddings from dotenv import load_dotenv import sys import os load_dotenv() OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') embedding = OpenAIEmbeddings() llm = chosen_llm() def uploadDocument(self, request): user = get_user(request) base64_data = request.data.get('file') # Create a record of the document in the SQLite database. document = Documents.objects.create(name=request.data.get( "name"), user=user, content=base64_data) document.save() # Convert the pdf into a big string. cleaned_text, documents = load_new_pdf(document) # Initiliaze the persistent client. client = chromadb.PersistentClient(path="../chroma") # Strip the user email from the '@' and '.' characters and get or create a new collection for it collection_name = strip_user_email(user.email) client.get_or_create_collection(collection_name) # Embed the documents into the database Chroma.from_documents( documents=documents, embedding=embedding, client=client) # Retrieve the collection from the database chroma_db = Chroma(collection_name=collection_name, embedding_function=embedding, client=client) print(chroma_db.get()["documents"], file=sys.stderr) # This is now [], why?? … -
Celery error received unregistered task of type, some of the nodes didn't update
I have a Django app on dokku with celery tasks. After updating the code, I sometimes encounter the "error received unregistered task of type X" for certain tasks. Previously, everything was working fine. When I run celery -A my_app inspect registered I get: -> celery@4ae2d1ac0e16: OK * campaigns.tasks.task1 * campaigns.tasks.task2_new * my_app.celery.debug_task * my_app.celery.fail_task -> celery@46d837d1ffd2: OK * campaigns.tasks.task1 * campaigns.tasks.task2 * my_app.celery.debug_task * my_app.celery.fail_task -> celery@dad78368f410: OK * campaigns.tasks.task1 * campaigns.tasks.task2_new * my_app.celery.debug_task * my_app.celery.fail_task 3 nodes online. One node (1/3) doesn't have the task2_new, and instead, it has the old version of the task task2 So when I call the task task2_new sometimes I get the error "Received unregistered task of type 'my_app.tasks.task2_new'" The problem is consistent, so I guess it is because some of the nodes are up to date and one isn't updated. How can I ensure that all celery nodes are updated whenever I upload a new version? I checked a lot of questions, but couldn't find anything that helped me. KeyError Received unregistered task of type '' on celery while task is registered Python Celery Received unregistered task of type - import app error Celery Received unregistered task of type (run example) Thanks! -
Customize the form used by Staff user to change password
In my project I need to set some certain fields to ltr direction because the whole project is in rtl direction so this is what I do: admin.py class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'].widget.attrs.update({'dir': 'ltr'}) self.fields['password1'].widget.attrs.update({'dir': 'ltr'}) self.fields['password2'].widget.attrs.update({'dir': 'ltr'}) class CustomUserChangeForm(UserChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'].widget.attrs.update({'dir': 'ltr'}) class CustomAdminPasswordChangeForm(AdminPasswordChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password1'].widget.attrs.update({'dir': 'ltr'}) self.fields['password2'].widget.attrs.update({'dir': 'ltr'}) class CustomPasswordChangeForm(PasswordChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['old_password'].widget.attrs.update({'dir': 'ltr'}) self.fields['new_password1'].widget.attrs.update({'dir': 'ltr'}) self.fields['new_password2'].widget.attrs.update({'dir': 'ltr'}) And then: class UserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm change_password_form = CustomAdminPasswordChangeForm The above 3 forms work as expected, however the CustomAdminPasswordChangeForm is for when the Superuser is changing the password. This form does not ask for Old Password. But when a Staff logs into Admin site, another form is used to change the password which asks for Old Password too. I have customized that form too (CustomPasswordChangeForm above) but I can't find how to set it in my UserAdmin class? -
Duplicate request with HTMX on the submit button of the form
with this code: <button class="button is-success" type="submit" hx-get="{% url 'refresh_navbar' %}" hx-target="#header" hx-trigger="submit" >Login</button> the post is executed (submited) (the post is done by the hx-post of the form actually) and this code without the hx-trigger: <button class="button is-success" type="submit" hx-get="{% url 'refresh_navbar' %}" hx-target="#header" >Login</button> executes the get request when i click in the button (but actually i want the get after the submission) and dosent execute the submission. How can i execute both requests after the form submission event. I can't put the get in the form, because it already has another target. <form class="form" name="form" hx-post = {{request.path}} hx-trigger="submit" hx-headers='{"X-CSRFToken":"{{ csrf_token }}"}' hx-target="#login-modal" > Thank you guys the full form is this, it's a modal. and the #header is in another template <form class="form" name="form" hx-post = {{request.path}} hx-trigger="submit" hx-headers='{"X-CSRFToken":"{{ csrf_token }}"}' hx-target="#login-modal" > {% csrf_token %} <div class="field"> <label class="label">Email</label> <div class="control"> {% render_field form.email class="input is-link" placeholder="user@example.com" name="email"%} {% if form.email.errors %} <p class="help is-danger">{{ form.email.errors|first }}</p> {% endif %} </div> </div> <div class="field"> <label class="label">Senha</label> <div class="control"> {% render_field form.password class="input is-link" placeholder="*********" name="password" %} {% if form.password.errors %} <p class="help is-danger">{{ form.password.errors|first }}</p> {% endif %} </div> </div> <div class="field"> <div class="control"> <button … -
AWS Elastic Beanstalk Django Project Health Check Fails
I have deployed a Django application to Elastic Beanstalk, in single instance type there is no problem and the health check is green, but when I choose the Load Balanced type and add HTTPs listener with a valid certificate from Amazon Certificate Manager,the health became Severe and also when I click on view causes it show me this (Process default has been unhealthy for 15 hours (Target.FailedHealthChecks)), I can access the website with the HTTPs and also HTTP, there is no problem, all settings are correct, I have the security group with inbound and outbound rules, but the health became severe. -
How to avoid LOGENTRIES_TOKEN spam logs in django?
When i run the python manage.py <somecmd>, i'm getting the below error: It appears the LOGENTRIES_TOKEN parameter you entered is incorrect! How can i disable this log, this log spamming across the access log. I've tried to control it using log_level as of now, but it's not working. -
Modify django action style
This's default action style. How shoul change it style to button, like this: I know it default rendering to <select>, but i wanted to rendering to each <button>. I tried custom ModelAdmin def get_action_choices but not succcess What should i do now? -
Online Marketplace Payment System
I'm building a website like ebay where sellers post listings and users can buy them. I want it so that buyers are able to pay sellers directly, and I take a percentage of the sale. Is Stripe Connect the correct product to use? I want it so that buyers do not need a stripe account to pay, they only need to enter their credit card info and hit pay. If not, what are some alternative payment systems I can use? -
EmailBackEnd.authentication() missing 1 required positional argument: 'request'
that is the error I get when I tried to log in I don't really know if something is missing in my login code please help me review this code this is my views.py if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: user = EmailBackEnd.authentication( request, username=request.POST.get("email"), password=request.POST.get("password"), ) if user != None: login(request, user) return HttpResponse( "Email : " + request.POST.get("email") + "password : " + request.POST.get("password") ) else: return HttpResponse("Invalid Login") def GetUserDetails(request): if request.user != None: return HttpResponse( "User : " + request.email.user + "usertype : " + request.user.user_type ) else: return HttpResponse("Please login first") def logout_user(request): logout(request) return HttpResponse("") EmailBackEnd.py from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmailBackEnd(ModelBackend): def authentication(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None urls.py from django.urls import path from school_system.EmailBackEnd import EmailBackEnd from . import views urlpatterns = [ path("", views.Login`your text`Page, name=""), path("get_user_details", views.GetUserDetails), path("logout_user", views.logout_user), path("user_login", views.user_login), path("", views.base, name=""), ] -
Getting the Djoser token
Hello everyone I'm new to development. There was a problem when receiving a token during authentication via Djoser. It seems that I do everything in accordance with the documentation but I do not get the necessary result I was trying to redefine the model to change the serializer settings REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } DJOSER = { 'LOGIN_FIELD': 'email', } serializer class CustomUserSerializer(UserSerializer): """Serializer for User""" is_subscribed = SerializerMethodField() def get_is_subscribed(self, obj): request = self.context.get("request") if request and not request.user.is_anonymous: user = request.user return Follow.objects.filter(user=user, author=obj).exists() return False class Meta: model = User fields = ( "email", "id", "username", "first_name", "last_name", "is_subscribed", ) -
Django - values() and group by month
I am stuck with a problem and not getting solution anywhere. columns in model are category date amount I need to get total of amount for each category and display in template for each month. Something like this Category---month1---Month2 A 100 180 B 150 200 I have tried below query but it does not seem to work. queryresult = model.objects.filter().values('category').annotate(total='amount') It do give total for each category but how do I arrange it monthwise. Basically total of category for each month? -
Trying to save the output from BabyAGI with Tools into the REST API Backend
My code structure is: React Frontend -> Textfield saves the (string) input successfully into the REST API Backend (Django) Django Backend -> In the utils.py file there I have this function that is basically 1:1 copied from here - Github --> Basically my function looks like this: def generateAgentAnswer(user_input): # Define your embedding model embeddings_model = OpenAIEmbeddings() embedding_size = 1536 index = faiss.IndexFlatL2(embedding_size) vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {}) todo_prompt = PromptTemplate.from_template( "You are a planner who is an expert at coming up with a todo list for a given objective. Come up with a todo list for this objective: {objective}" ) todo_chain = LLMChain(llm=OpenAI(temperature=0), prompt=todo_prompt) search = SerpAPIWrapper() tools = [ Tool( name="Search", func=search.run, description="useful for when you need to answer questions about current events", ), Tool( name="TODO", func=todo_chain.run, description="useful for when you need to come up with todo lists. Input: an objective to create a todo list for. Output: a todo list for that objective. Please be very clear what the objective is!", ), ] prefix = """You are an AI who performs one task based on the following objective: {objective}. Take into account these previously completed tasks: {context}.""" suffix = """Question: {task} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, … -
Django query to sum first value in a nested fforeign key
Given the three below models class GrandFather(models.Model): pass class Father(models.Model): grandfather = models.ForeignKey(GrandFather) class Son(models.Model): father = models.ForeignKey(Father) date = models.DateField() value = models.IntegerField() What would the annotate command be to get the sum of the value of the latest son for each father, for all fathers in a grandfather. I can do a subquery, but don't know how to do a nested subquery. Don't know how to even go at that! -
Has anyone been able to deploy a Django project to elasticbeanstalk by uploading a zip file?
I have been able to deploy django projects using: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html , which is deployment from terminal on my mac. But I haven’t been able to do it by uploading a zip file. “ebdjango” is the name of my project. django.config contains: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application requirements.txt contains: asgiref==3.7.2 Django==4.2.9 sqlparse==0.4.4 typing_extensions==4.9.0 I am not sure if there is something wrong with how I create the zip file because i get the warning message: “Configuration files cannot be extracted from the application version ebdjango. Check that the application version is a valid zip or war file.” What I do is I compress .ebextensions, ebdjango manage.py and requirements.txt . When I open the zip file there is a root folder with the same name as the zip file and that folder contains .ebextensions, ebdjango manage.py and requirements.txt . Is it supposed to be like that or is everything supposed to be extracted from the zip when i open it without a parent folder? Is this why I can’t deploy my django project to elasticbeanstalk? -
Django ORM: "TypeError: 'list' object is not callable"
I've added class methods for the model. After adding them, it stopped working, gives me a type error. Migrations also don't work. These classes calculate the price with and without discount. Now quantity throws an error, suddenly becoming a 'list' object models class OrderItem(models.Model): price = models.DecimalField(max_digits=9, decimal_places=2) quantity = models.IntegerField(default=1) order = models.ForeignKey( Order, on_delete=models.CASCADE, blank=True, null=True, related_name='items') product = models.ForeignKey( Product, on_delete=models.CASCADE, blank=True, null=True) user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return "Item" + str(self.id) def get_cost(self): return self.price * self.quantity @property def total_cost(self): return self.price * self.quantity @classmethod def get_total_quantity_for_product(cls, product): return cls.objects.filter(product=product).aggregate(total_quantity=models.Sum('quantity'))[ 'total_quantity'] or 0 @staticmethod def get_average_price(): return OrderItem.objects.aggregate(average_price=models.Avg('price'))['average_price'] admin.py code import csv import datetime from django.contrib import admin from django.http import HttpResponse from django.urls import reverse from django.utils.html import format_html from django.utils.safestring import mark_safe from .models import Order, OrderItem, ShippingAddress def export_paid_to_csv(modeladmin, request, queryset): opts = modeladmin.model._meta content_disposition = f"attachment; filename=Paid{opts.verbose_name}.csv" response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = content_disposition writer = csv.writer(response) fields = [ field for field in opts.get_fields() if not field.many_to_many and not field.one_to_many ] writer.writerow([field.verbose_name for field in fields]) for obj in queryset: if not getattr(obj, "paid"): continue data_row = [] for field in fields: value = getattr(obj, field.name) if isinstance(value, … -
django get duplicated row pk
My goal is to update every day my database records by uploading a file containing the 7 past days data. If a record already exists, I would like to update it with the new one in the file we are uploading, otherwise create a new record and save it. An existing record is when we have the same date, the same advertiser, and the same insertion_order. I no more want to raise an exception error about those duplicated rows but handling them by updating them with the news ones. Could you please help me ? try: df.to_sql( dsp, # Xandr._meta.db_table, if_exists="append", index=False, dtype=dtype, chunksize=1000, con=engine, ) except IntegrityError: msg = "Duplicated rows are not authorized." raise Exception(msg) the model class Xandr(InsertionOrdersCommonFields): dsp = models.CharField("Xandr", max_length=20) class Meta: db_table = "Xandr" unique_together = [ "date", "advertiser", "insertion_order" ] verbose_name_plural = "Xandr" def __str__(self): return self.dsp The error I got -
Celery & Django - does the main process wait for tasks to finish?
I've just started work on a project that uses Django & Celery. I'm quite new to both. One of the endpoints has code that looks like this: task_make_report.delay() return Response( {"success": True}, status=status.HTTP_200_OK ) task_make_report is a task that takes a while to complete. (It does not call any other Celery tasks.) Will the main process execute the return statement immediately after Celery queues the task? Or will it wait for the task to be complete before moving on to the next line? Reading through the documentation, I'm inclined to think that the answer would be the first option (execute next statement after the task is queued), because Celery tasks are asynchronous. But I'd like to double-check. -
Google auth in react js(npm vite)
I'm making a inventory system which requires to sign up using their google account. My problem is I don't know how to use google api request in npm vite. Does anyone know how to do it? As a beginner I don't know where to begin. My backend that I'm using is django. Meanwhile in the frontend is NPM vite. -
django-rest-framework authentication and permission. Prevent authenticated user from posting if user is is_staff=false, is_superuser=false
I have a class based APIVIEW and I want to prevent a normal user (isstaff=false, is_superuser=false) from creating a customer. class CustomerPageView(APIView): # permission_required = 'api.view_customer' permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get(self, request): customer = Customer.objects.all() # Check if there is a customer if not customer.exists(): return JsonResponse([], safe=False) customer_serializer = CustomerSerializer(customer, many=True) return JsonResponse(customer_serializer.data, safe=False) def post(self, request): data = json.loads(request.body.decode('utf-8')) company_name, contact_person, contact_number, company_address = data.values() company_name = company_name.strip() # Check if item exists chk_company_name = Customer.objects.filter(company_name__iexact=company_name) if chk_company_name: return JsonResponse({'label':'company_name', 'message':'Customer Already Exists'}, status=500) if len(company_name) == 0: return JsonResponse({'label':'company_name', 'message':'Invalid Entry'}, status=500) createCustomerInstance = Customer.objects.create( company_name=company_name, contact_person=contact_person, contact_number=contact_number, company_address=company_address, ) return JsonResponse({'message': f"Successfully added {company_name}", 'variant': 'success'}) enter image description here this user currently don't have any permissions. However when I logged in as normal user I can still create a customer. -
How to serialize many-to-many-to-one relationship in Django Rest Framework
I have a many-to-many-to-one relationship I would like to represent in DRF. I can get the relevant fields using a SerializerMethodField but it feels like there should be a cleaner way. Setup: from django.db import models from rest_framework import serializers class Textbook(models.Model): id = models.AutoField(primary_key=True) class ETextBook(models.Model): id = models.AutoField(primary_key=True) textbook = models.OneToOneField(Textbook, on_delete=CASCADE, related_name="etextbook") class Author(models.Model): id = models.AutoField(primary_key=True) textbooks = models.ManyToManyField(Textbook, related_name="authors") class ETextBookSerializer(serializers.ModelSerializer): class Meta: model = ETextBook fields = "__all__" Ugly working solution: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ("id", "textbooks", "etextbooks") etextbooks = serializers.SerializerMethodField() def get_etextbooks(self, obj): etextbooks = ETextbook.objects.filter(textbook__authors=obj) return ETextBookSerializer(etextbooks, many=True).data But what I'd really like to do is: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ("id", "textbooks", "etextbooks") etextbooks = ETextBookSerializer(source="textbooks.etextbook", many=True) but this raises a: Traceback (most recent call last): File "/Users/scottgigante/envs/django/lib/python3.11/site-packages/rest_framework/fields.py", line 446, in get_attribute return get_attribute(instance, self.source_attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/scottgigante/envs/django/lib/python3.11/site-packages/rest_framework/fields.py", line 96, in get_attribute instance = getattr(instance, attr) ^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'ManyRelatedManager' object has no attribute 'etextbook' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/scottgigante/envs/django/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/scottgigante/envs/django/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/scottgigante/envs/django/lib/python3.11/site-packages/django/views/decorators/csrf.py", … -
django exclude for foreign Key related and count elements
is a representation the basic django model relations STATIONS_MODEL state name ROUTER ForeignKey(ROUTERS) TICKET_MODEL STATIONS ForeignKey(station, related_name"ticketforstation") softDelete = bool IN VIEW TEMPLATE context['stations'] = stations_model.objects.all() IN TEMPLATE {% for station in stations %} <div class="container"> {{station.name}} <span>{{station.ticketforstation.all.count}}</span> </div> {% endfor %} I needed count only SOFTDELETE is FALSE ALSO SIMILAR A IN TEMPLATE {% for station in stations %} <div class="container"> {{station.name}} <span>{{station.ticketforstation.(SOFTDELETED FALSE).count}}</span> </div> {% endfor %} I don't have idea as with resolved this... -
Django atomic block for create with an unique field
I have a model similar to the following: Class MyModel(models.Model): my_field = models.CharField(max_length=30, default='', unique = True) And the following code to create new instances of the model: with transaction.atomic(): try: instance, _ = MyModel.objects.select_for_update().get_or_create( my_field=value) except (IntegrityError, OperationalError): pass return instance As of my understanding, the entire table is locked by the select_for_update. Another alternative would be catching the UniqueConstraintError after it occurs. Is there any way, to avoid having an UniqueConstraintError, without locking the entire table? -
Connection Refused Error: [Errno 111] Connection refused - Getting error for Mailtrap SMTP
I am trying to register user which should send activation code to the dummy server. But while sending the post request from the Insomnia getting 500 internal error. And using Djoser for the email communication (authentication and authorization) Checked telnet to the smtp server telnet sandbox.smtp.mailtrap.io 2525 Trying 54.158.84.126... Connected to mailsend-smtp-classic-f3a4534c019a3e96.elb.us-east-1.amazonaws.com. Escape character is '^]'. 220 smtp.mailtrap.io ESMTP ready Backend settings EMAIL_HOST=sandbox.smtp.mailtrap.io EMAIL_PORT=2525 EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL = env("EMAIL_HOST") EMAIL_USE_TLS = True EMAIL_PORT = env("EMAIL_PORT") EMAIL_HOST_USER = env("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD") DAFAULT_FROM_EMAIL = "XXXX" DOMAIN = env("DOMAIN") SITE_NAME = "XXXX" DJOSER = { "LOGIN_FIELD": "email", "USER_CREATE_PASSWORD_RETYPE": True, "USERNAME_CHANGED_EMAIL_CONFIRMATION": True, "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True, "SEND_CONFIRMATION_EMAIL": True, "PASSWORD_RESET_CONFIRM_URL": "password/reset/confirm/{uid}/{token}", "SET_PASSWORD_RETYPE": True, "PASSWORD_RESET_CONFIRM_RETYPE": True, "USERNAME_RESET_CONFIRM_URL": "email/confirm/{uid}/{token}", "ACTIVATION_URL":"activate/{uid}/{token}", "SEND_ACTIVATION_EMAIL": True, } Not sure what is missing piece.