Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you control which language get stored in your models?
I am making a GraphQLAPI for a local business in my area using django_graphene. We will only be dealing with our local language and there will be no english used except for maybe email and password. When I get data from user I want to check if the language that the user typed in is in my preferred language and then store it in the database. How do I control the language being stored in the database? -
Python import all from folder
I have encountered issue while working on my Django project. I have multiple classes inside views.py. It had 1200 lines so I decided to move these views to seperated files inside new folder. Now one files, for example Customer.py has 2 classes for different operations. This is my project structure before splitting views.py: MyProject core - urls.py api - views.py manage.py Project structure after splitting views.py MyProject core - urls.py api - view - *all the files with multiple classes in each file* manage.py After splitting views.py I needed to import all classes from all files inside of the view folder inside core/urls.py. I have been trying to find out few hours now and can figure it out... My current solution is that in urls.py im doing from api.view import * while having init.py inside view folder which is doing from .oneOfManyClasses import * for all classes... I highly dont like this solution, I would love to find out some good looking simple elegant solution. Is here anyone who can help me ? Big thanks -
Django change frontend validation of number input widget
For number fields in the Django admin interface, it's only possible to input numbers and separators. How can I implement a similar frontend validation for my own custom widget? For example, I want to extend a TextInput widget so that the user can only input [A-Za-z]. The included pattern attribute only validates in the backend. -
Python - Compare two JSON with different length and without order
I want to compare two json data without order because there are same items with different orders. For example first json: [{'Id': 113, 'Label': 'Z', 'Input': 'Z', 'Updated': False}, {'Id': 124, 'Label': ' X', 'Input': ' X', 'Updated': False}, {'Id': 128, 'Label': ' C', 'Input': ' C', 'Updated': False}, {'Id': 117, 'Label': ' R', 'Input': ' R', 'Updated': False}, {'Id': 118, 'Label': ' T', 'Input': ' T', 'Updated': False}] Second Json [{'Id': 128, 'Label': ' C1', 'Input': ' C1', 'Updated': False}, {'Id': 118, 'Label': ' T1', 'Input': ' T1', 'Updated': False} {'Id': 113, 'Label': 'Z2', 'Input': 'Z2', 'Updated': False},] I want to make update different data but same ID json from the second json and delete from the first Json what second json doesnt have. So my loop is below: for form in selectedUserForm: for jsonItem in getJson: if form.id == jsonItem['Id'] and form.isUpdated == False: form.metaKey = jsonItem['Label'] form.metaVal = jsonItem['Input'] form.isUpdated = True form.save() elif jsonItem['Id'] == 0: newMeta = UserMeta(user = selectedUser, metaVal = jsonItem['Input'].title(), metaKey = jsonItem['Label'].title(), isUpdated = True) newMeta.full_clean() newMeta.save() elif form.isUpdated == False: form.isDeleted = True form.isUpdated = True form.save() However, this algorithm only make with order but my list is posted from … -
NoReverseMatch at /sessions/exercise/6/update/
I'm going crazy here. According to the Django debugger there's no reverse match for the pattern I'm requesting, but it's identical to my URL path in urls.py, and I am passing the object id as the required argument. NoReverseMatch at /sessions/exercise/4/update/ Reverse for 'exercise_update' with no arguments not found. 1 pattern(s) tried: ['sessions/exercise/(?P[0-9]+)/update/$'] Error during template rendering This is my html <button><a href="{% url 'sessions:exercise_update' exercise.id %}">Update exercise</a></button> This is my URL path path('exercise/<int:pk>/update/', MyExerciseUpdate.as_view(), name='exercise_update'), The view is just a generic update view. class MyExerciseUpdate(LoginRequiredMixin, UpdateView): model = Exercise fields = ['my_fields'] I've tried displaying the exercise.id just to see if it exists, and it does. How come there is no argument? Also, I use this path for a detail view in another page and it works just fine <a href="{% url 'sessions:exercise_detail' exercise.id %}">{{ exercise.name }}</a> Help, please. -
Django how to check if user is in path
I made an unique url and I want to check if the acutal url contains the uid so I made a if statement which is always false in my case so what can I change that it works and checks if the path contains the uid. views.py @login_required(login_url='home:login') def ChangeEmailView(request, token): packet = get_object_or_404(TempUrl, user=request.user) token = packet.uid if request.path == str(token): if request.method == 'POST': objects = User.objects.get(email = request.user.email) form = EmailChangingForm(request.POST, instance=objects) if form.is_valid(): form.save() return redirect('home:profilesettings') else: objects = User.objects.get(email = request.user.email) form = EmailChangingForm(request.POST, instance=objects) packet = get_object_or_404(TempUrl, user=request.user) token = packet.uid else: print('site wasnt found') objects = User.objects.get(email = request.user.email) form = EmailChangingForm(request.POST, instance=objects) packet = get_object_or_404(TempUrl, user=request.user) token = packet.uid return redirect('home:index') context = {'form': form, 'token': token} return render(request, 'home/email_settings.html', context) -
AssertionError at /api/ Expected a `date`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information
I am creating an API and have some problems: title = models.CharField(max_length=250,default='') description= models.CharField(max_length=1000) start_date = models.DateField(blank=True,null=True) end_date = models.DateField(blank=True,null=True) reg_start_date = models.DateField(blank=True,null=True) reg_end_date = models.DateField(blank=True,null=True) input_date = models.DateTimeField(default=timezone.now) author = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='yoga_tours') slug = models.SlugField(max_length=250, unique_for_date='input_date') status = models.IntegerField(choices=statuses,default=1) objects = models.Manager() # default manager tourobjects = TourObjects() # custom manager serializers.py class YogatourSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'title', 'description', 'start_date', 'end_date', 'reg_start_date','reg_end_date','author','status') model = Yogatour I want to have date field only, without time properties .when I post something, I am getting next error: AssertionError at /api/ Expected a `date`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information. Use a custom read-only field and deal with timezone issues explicitly. how to solve this problem? -
Use different decimal separators for frontend validation in Django Admin interface
I looked through every single similar question on stackoverflow and tried nearly everything. It seems easy to do: I just want to allow , as decimal separator for a FloatField in the Django admin interface. At the moment, it depends on the localization, but I always want to allow it. It would even be ok for me, if it's just a TextInput, but I need , to work. Setting DECIMAL_SEPARATOR in settings.py does not work. My question is similar to this 6 year old, unanswered one: How to only override DECIMAL_SEPARATOR in django while keeping localization intact? I managed to use the TextInput widget for FloatFields like this: class ExampleAdminForm(forms.ModelForm): class Meta: model = Example def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for key, value in self.fields.items(): if isinstance(value, FloatField): self.fields[key].widget = TextInput() The widget works, but an input like 1,23 leads to an error message Enter a number. I can't find out where the validation happens, as validate() of FloatField never gets triggered. Is there a way to, for example, override FloatField or the TextInput widget to allow for other decimal separators? Or any other way? -
Django - Transfer data from view to form
I am struggling with the update of database information with the forms, and simply passing information between views. I could really use some advice because I am fairly new to Django. The flow goes like this: 1. First form; I transfer the article price and title to the view "event" 2. The view "event" handles title and price and ask for confirmation in the html form 3. Once confirmed, it directs that information to the view "transact_test", I want this view to handle the update of the database via a new form that is build with the Article model. But it provides the error message : "didn't return an HttpResponse object. It returned None instead." -
(Django) Edit form data that is not ModelForm
Currently I'm having a Form model (unfortunately not ModelForm) with data which need to be edited/updated. After looking through many posts (most of which were related to ModelForm), I found a way to edit/update the data of Form inside Django shell with the following syntax: Drug.objects.filter(drug_id='d61').update(drug_id='d7') It worked inside the shell, yet when I did the same thing in the html form, nothing happened: data remained unchanged, no error was raised. drugs/forms.py from django import forms class DrugForm(forms.Form): drug_id = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'id': 'drug_id', 'data-val': 'true', 'data-val-required': 'Please enter drug id', })) name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'id': 'name', 'data-val': 'true', 'data-val-required': 'Please enter name', })) updated_date = forms.CharField(widget=forms.DateInput(attrs={ 'class': 'form-control', 'type': 'date', 'id': 'update_date', }), required=False) drugs/models.py from django.db import models class Drug(models.Model): drug_id = models.CharField(max_length=20, unique=True, error_messages={'unique':"This drug id has already been registered."}) name = models.CharField(max_length=50) updated_date = models.DateField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.name drugs/views.py from django.shortcuts import render, redirect from django.views.generic import ListView from django.shortcuts import get_object_or_404 from .models import ( Drug, ) def update(request, drug_id): drug = get_object_or_404(Drug, drug_id=drug_id) drug_id = drug.drug_id name = drug.name updated_date = drug.updated_date if updated_date == '': updated_date = None Drug.objects.filter(drug_id=drug_id).update(drug_id=drug_id, name=name, updated_date=updated_date) return redirect("drug-list") templates/drugs/edit_drug.html {% extends 'base/base.html' … -
How to convert function base view to Generic class based for two models
i create a register view as function based, but i want to use generic class to improve my code better. this is my models.py from django.db import models from django.contrib.auth.models import User class UserRegister(models.Model): reg_user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='user') mobile = models.CharField(max_length=255, verbose_name='mobile phone number : ', unique=True) name = models.CharField(max_length=255, verbose_name='First Name : ') family = models.CharField(max_length=255, verbose_name='Last Name : ') def __str__(self): return f"{self.mobile} as {self.name}" then my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from .models import * class RegisterForm(UserCreationForm): class Meta: model = User fields = ['username', 'first_name', 'email', 'password1', 'password2'] class UserForm(forms.ModelForm): class Meta: model = UserRegister fields = '__all__' then i called them both in views.py like this from django.shortcuts import render, redirect from django.views.generic import * from .forms import * def register(request): r_form = RegisterForm() u_form = UserForm() if request.method == 'POST': r_form = RegisterForm(request.POST) u_form = UserForm(request.POST) if r_form.is_valid() and u_form.is_valid(): user = r_form.save() u_form = u_form.save(commit=False) u_form.user = user u_form.save() return redirect('main') else: r_form = RegisterForm(request.POST) u_form = UserForm(request.POST) context = { 'r_form': r_form, 'u_form': u_form } return render(request, 'template.html', context) an example of generic class based that i know is only store to 1 models like class CreateUserView(CreateView): … -
DateTimeField: how to retrieve date in my local time
settings.py TIME_ZONE = 'Asia/Kolkata' models.py order_booking_time = models.DateTimeField() while creating: "order_booking_time":"2021-10-09 06:00" What it stores in database: "2021-10-08T18:53:17.097257+05:30" So i did this in serializer.py while viewing in data def get_order_booking_time(self,obj): date = obj.order_booking_time.strftime("%Y-%m-%d %H:%M:%S") return str(date) Output: "2021-10-09 00:30:00" which is not equal to what i stored in data i.e."2021-10-09 06:00" What in the way we retrieve OR store data in this "%Y-%m-%d %H:%M:%S" format with my local time -
NoReverseMatch at /news/
I have looked through a lot of questions but I still can't find an answer. NoReverseMatch at /news/ Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/news/ Django Version: 3.2.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. Exception Location: C:\Users\retar\anaconda3\envs\pc\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\retar\anaconda3\envs\pc\python.exe Python Version: 3.9.6 Python Path: ['C:\Users\retar\Desktop\polygon\fotonika', 'C:\Users\retar\anaconda3\envs\pc\python39.zip', 'C:\Users\retar\anaconda3\envs\pc\DLLs', 'C:\Users\retar\anaconda3\envs\pc\lib', 'C:\Users\retar\anaconda3\envs\pc', 'C:\Users\retar\anaconda3\envs\pc\lib\site-packages'] Server time: Fri, 08 Oct 2021 13:15:03 +0000 models.py class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField(blank=True) created_at = models.DateTimeField(auto_now=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) is_published = models.BooleanField(default=True) category = models.ForeignKey('Category',on_delete=models.PROTECT, null=True,) def get_absolute_url(self): return reverse('post_detail', kwargs={"pk": self.pk}) def __str__(self): return self.title news.urls from django.urls import path from . import views app_name = "news" urlpatterns = [ path('',views.PostListView.as_view(),name='all_news'), path('<int:pk>/', views.PostDetailView.as_view(), name='post_detail'), urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path,include from fapp import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.HomePage.as_view(),name='home'), path('news/',include('news.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) all_news.html {% extends 'base.html' %} {% block content %}<h1> NEWS PAGE</h1> {% for post in posts %} <a href="{{ post.get_absolute_url }}">{{post.title}}</a> {% endfor … -
The same name for different models in different Django applications
I have application 1 and application 2 in a Django project. I need each application to have its own table named Task and File. And the File table in each app refers ForeignKey to the Task table in its own app. It looks like this: app1.models class Task(BasicTask): task_id = models.IntegerField(primary_key=True) class File(BasicFile): file_id = models.AutoField(primary_key=True) task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='Task_one') app2.models class Task(BasicTask): task_id = models.IntegerField(primary_key=True) class File(BasicFile): file_id = models.AutoField(primary_key=True) task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='Task_two') main.models class BasicTask(models.Model): name = models.TextField() priority = models.IntegerField() status = models.IntegerField(default=0) user = models.ForeignKey( CustomUser, on_delete=models.CASCADE, null=True, related_name='+') def __str__(self): return f"{self.id}. {self.name}" class BasicFile(models.Model): unique_id = models.TextField() status = models.IntegerField(default=0) user = models.ForeignKey( CustomUser, on_delete=models.CASCADE, null=True, related_name='+') content = models.TextField() def __str__(self): return f"{self.id}. {self.unique_id}" The problem is that I get the following errors when I make migrations: ERRORS: app2.Task.basictask_ptr: (fields.E304) Reverse accessor for 'app2.Task.basictask_ptr' clashes with reverse accessor for 'app1.Task.basictask_ptr'. HINT: Add or change a related_name argument to the definition for 'app2.Task.basictask_ptr' or 'app1.Task.basictask_ptr'. app2.Task.basictask_ptr: (fields.E305) Reverse query name for 'app2.Task.basictask_ptr' clashes with reverse query name for 'app1.Task.basictask_ptr'. HINT: Add or change a related_name argument to the definition for 'app2.Task.basictask_ptr' or 'app1.Task.basictask_ptr'. app1.Task.basictask_ptr: (fields.E304) Reverse accessor for 'app1.Task.basictask_ptr' clashes with … -
How to create a dynamic filter sidebar with Django and React?
We have to develop a simple homepage showing multiple electronic products and want to add a side bar filter that shows fields dynamicaly with the total of products based on previous filtered queryset. For example: Brand ----- Acer [11] LG [9] Lenovo [12] RAM --- 8Gb [6] 16Gb [16] Let's imagine LG does not have any laptop with 8Gb RAM, so if the user filters by 8Gb, the result will be: Brand ----- Acer [4] Lenovo [2] RAM --- [x] 8Gb [6] Which is the best way to handle this using Django and React? -
Django: Pagination on object, in view with multiple items in context-list
I use below code in my view to generate a page, based on a default "layout.html", and include "items.html" which has the object list in it to iterate through and print the items. However, I want to apply Django's pagination functionality, on the item object. How do I go about this? Sorry if this is an easy question; just got into Django from a PHP background. def Items(request): context = { "item": Items.objects.all(), "page": "items.html", } return render(request, 'layout.html', context) -
Django AttributeError: 'Model' object has no attribute 'field'
I'm new to Django and I'm trying to create a simple test project with one Customer model. models.py: from django.db import models class Customer(models.Model): first_name = models.CharField(name='First name', max_length=20) last_name = models.CharField(name='Last name', max_length=20) def __str__(self) -> str: return self.first_name However, when I try to enter this table in the admin console, it throws an error AttributeError: 'Customer' object has no attribute 'first_name'. I've tried to rerun the server, but it doesn't help. If I change the method to something else, then the problem disappears: def __str__(self) -> str: return "1" But I need to have first_name as a basic presentation of my Customer objects. So what did I miss? -
Drag and Drop parts of an image as separate images
I am trying to develop a front-end feature where the user can drag and drop parts of an image (texts detected via Google Vision API for OCR) to different <div>s to categorize detected texts on the image. For example, in the picture below, I want 'Moreno', 'Kaffeepads', '40 pads' etc. to enable dragging and dropping these texts on the original image as separate images to other divs. However, I'm not completely sure how to implement such feature. I am implementing the backend with Django. Any suggestion would be appreciated. -
how to retrieve data from django backend using react
Is there a ReactJS library that allows me to get the data sent by django rest framework backend? views.py @api_view(["GET"]) def some_view_url(request): if request.method == "GET": context = {"token": "someBase64Code"} return Response(context) From the front end, i want to access context and get the value of token I don't like the route of modifying the script tag manually... and i am trying to find something else that what is mentioned in django documentation with the getCookie function or using js-cookie in the front end. -
"local variable 'shipment_booking' referenced before assignment" How can i solved this
**shipment_booking is my table name. ***i want to check my table filed "ord" value is "yes" or not ****if my "ord"field value "yes" then return "pre-budget" page. def bkp1(request): orderv="yes" allorder=shipment_booking.objects.all() return render(request, 'bkp1.html') if request.method=='POST'and 'pbd' in request.POST: for shipment_booking in allorder: o=shipment_booking.ords if orderv==o: return render(request, 'Pre-Budget.html') else: return render(request, 'bkp1.html',{'msg':'Please Add Order Details'}) else: return render(request, 'bkp1.html') -
Why am I getting a 'django.db.utils.ProgrammingError: relation "auth_user" does not exist' when running tests?
Recently I've migrated a Django project from version 1.9.1 to 3.2.7. Now I'm trying to write some new tests, and I'm getting this error: # python manage.py test Creating test database for alias 'default'... Got an error creating the test database: database "test_django" already exists Type 'yes' if you would like to try deleting the test database 'test_django', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "/opt/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist I understand this is because currently I don't have any 'migrations' directory, as I cloned the git repo and the DB already existed when the Django project was running in version 1.9.1. I've read: This question. Also this one. Also this. All of them recommend running migrations, but: # python manage.py makemigrations No changes detected # python manage.py makemigrations auth No changes detected in app 'auth' Again, I think this is because the DB schema already existed before upgrading to 3.2. I cannot seem to solve the issue running the migrations approach. Is there another way to solve this issue, or force to generate the migrations even if the DB … -
How to post prepopulated disabled ModelMultipleChoiceField?
I need my ModelMultipleChoiceField to be prepopulated with query parameters from GET-request (/?extending=1&extending2). I know from this question that I can define get_initial() method for my view, returning my request. And everything works fine until I disable the ModelMultipleChoiceField, since I don't need it to be mutable. This is my ModelForm class deduced from this answer: class ExtensionForm(forms.ModelForm): class Meta: model = Record fields = ['extending', 'name', 'description', 'picture', 'content', 'files'] extending = forms.ModelMultipleChoiceField(queryset=Record.objects.all()) def __init__(self, *args, **kwargs): if kwargs.get('instance'): initial = kwargs.setdefault('initial', {}) initial['extending'] = [el.pk for el in kwargs['instance'].extending.all()] forms.ModelForm.__init__(self, *args, **kwargs) self.fields['extending'].disabled = True def save(self, commit=True): instance = forms.ModelForm.save(self, False) old_save_m2m = self.save_m2m def save_m2m(): old_save_m2m() instance.extending.clear() instance.extending.add(*self.cleaned_data['extending']) self.save_m2m = save_m2m if commit: instance.save() self.save_m2m() return instance How do I update this class in order for my request to get there? -
Save progress or actions of user in django?
I have a serious of task which needs to be completed by users when they signup ! How to keep track on this ? For now am checking if data exsist in more than 5 tables (like address, education etc). I think this is not a good way of doing this ! As when ever user logins, i need to check if they have finished all the basic tasks and then allow them to do other things.. On doing research, i have few options: Option1: Create a new model and store all progress on each row and then fetch all the rows to check if required is completed. Option2: Create a new model and store the finished actions in a array, for instace: Class Actions: owner = models.ForeignKey(User, on_delete=models.CASCADE) actions = ArrayField(models.CharField(max_length=128)) And with these, i can append all the finished task one by one, like {emailverification, personal_details,education_details} etc And then use the above to work on the conditions I think the second option is more effective, as it just fetches on row from the table instead of fetching multiple rows ! Or please suggest any new option to track this ! -
Show django filter options according to the logged-in user
I’m new to Django and am trying to show filter options that are only relevant to the user - for example, my app has Message and Automation classes with a many:many relationship, but my filter shows a select option with automations created by other users rather than only those created by the logged-in user. How can I get it to only show those created by the current user? The view: @login_required(login_url='login') @allowed_users(allowed_roles=['admin', 'customer'], own_account_only=True) def message_list(request, pk): account = Account.objects.get(id=pk) messages = account.message_set.all() filter = MessageFilter(request.GET, queryset=messages) messages = filter.qs context = {'account': account, 'messages': messages, 'filter': filter} return render(request, 'messages/message_list.html', context) The filter: class MessageFilter(django_filters.FilterSet): class Meta: model = Message # model we’re building filter for fields = '__all__' exclude = ['account', 'date_created', 'text', 'subject'] The classes: class Message(models.Model): name = models.CharField(max_length=100) subject = models.CharField(max_length=128) text = models.TextField() account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) automations = models.ManyToManyField('automations.Automation', blank=True) def __str__(self): return self.name class Automation(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) messages = models.ManyToManyField(Message, blank=True) def __str__(self): return self.name And the HTML: <form method="get" class="filter-form with-ps hide"> {{filter.form.as_p}} <button class="button" type="submit">Search</button> </form> I’m assuming I need to edit the messages … -
Django User reset password, MongoDB to store user information
I am working on Django to reset user password. But all my user information are stored in MongoDB and not the default User table provided. All examples given in StackOverflow and elsewhere use the default User authentication mechanism which is not helping me. I need to generate an email link when user needs to reset password. Forms.py class EmailForPasswdChange(UserCreationForm): username = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'placeholder': 'Enter your username'}), required=True) password1 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'placeholder': 'Enter your username'}), required=False) password2 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'placeholder': 'Enter your username'}), required=False) class Meta: model = User fields = [ 'username', ] Views.py def sendEmail(request): if request.method == 'POST': form = EmailForPasswdChange(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.is_active =False current_site = get_current_site(request) username = request.POST.get('username') print(username) subject = 'Your Request for Password Reset' message = "Your Password will be reset" message = render_to_string('email_activation_link.html', { 'username':username, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(username)), 'token': token, }) from_email = settings.EMAIL_HOST_USER recipient_list = (email,) print (recipient_list) send_mail(subject, message, from_email, recipient_list) return render (request, 'user/forgotpasswd.html', {'inform': "EMail sent for resetting Password"}) else: print (form.errors) return render (request, 'user/forgotpasswd.html', {'inform': "EMail Not sent"}) Since I have customized UserCreationForm, on the template rendered, if I enter a username whose password is to be …