Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete a json row if all row is zero?
I have complex JSON data and I am creating a table from this data. I can get all values clearly. But I want to remove or hide a row if all data is zero. In my case, if my counter is 5 then I should remove 'title' and 'values' I created a function for that but I cannot remove the line. How can I do it? for data1 in financial_balance: for data2,key in data1.items(): if isinstance(key, str) != True: for k in key: for l,d in k.items(): if isinstance(d, str) != True: for x in d: count1 = 0 counter = 0 for e in x["values"]: count1 += 1 if e["value"] == 0: counter += 1 if counter == 5: # remove row my data: [ { 'name': 'Balance Sheet', 'dataList': [ { 'mainEntry': 'Assets', 'titles': [ { 'title': 'Trade', 'values': [ { 'yea r': 2020, 'value': 268057, 'colorCode': None }, { 'year': 2019, 'value': 421621, 'colorCod e': None }, { 'year': 'Year over year trends 2019 vs 2020', 'value': -0.36, 'colorCode': None }, { 'year': 'Common Size Analysis 2020', 'value': 0.12, 'colorCode': None }, { 'year': 'Common Size Analysis 2019', 'value': 0.14, 'colorCode': None } ] }, { 'title': … -
Validate model field in single line
approximation = models.IntegerField(null=False, default=None) I need to validate this field. It should be greater than 0 but i don't want to make function. -
How do I delete a record in django_admin_log?
So I have been making some (big) changes in my User model, and somehow got this error : django.db.utils.IntegrityError: The row in table 'django_admin_log' with primary key '1' has an invalid foreign key: django_admin_log.user_id contains a value '1' that does not have a corresponding value in member_user.id. The cause of the error is the superuser I created. But then I changed my User model from Django's built-in model to custom model.I'm trying to delete the record from the table django_admin_log which has user_id equal to 1. How do I do this? Thanks in advance. -
Django - Serving production using Apache2
Days I struggle with this. I have a django webapp written in Python 3.10 that works fine when launched using pipenv shell then python3.10 manage.py runserver. Also, doing python3.10 app/wsgi.py quits without any error. Now I want it to be served by Apache2. Here is my conf file: Listen 8000 <VirtualHost *:8000> ServerAdmin webmaster@localhost DocumentRoot /opt/app ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined LogLevel Debug Alias /static /opt/app/static <Directory /opt/app/static> Require all granted </Directory> <Directory /opt/app/app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /opt/app/app/wsgi.py WSGIDaemonProcess app python-home=/opt/app python-path=/opt/app/app:/usr/local/lib/python3.10:/usr/local/lib/python3.10/lib-dynload:/usr/local/lib/python3.10/site-packages WSGIProcessGroup app </VirtualHost> Results in HTTP 500 when navigating to my website. Apache2 error logs: [core:notice] AH00094: Command line: '/usr/sbin/apache2' [wsgi:info] mod_wsgi (pid=25232): Attach interpreter ''. [wsgi:info] mod_wsgi (pid=25232): Adding '/opt/app/app' to path. [wsgi:info] mod_wsgi (pid=25232): Adding '/usr/local/lib/python3.10' to path. [wsgi:info] mod_wsgi (pid=25232): Adding '/usr/local/lib/python3.10/lib-dynload' to path. [wsgi:info] mod_wsgi (pid=25232): Adding '/usr/local/lib/python3.10/site-packages' to path. [wsgi:info] [remote 192.168.3.110:37296] mod_wsgi (pid=25232, process='app', application=''): Loading Python script file '/opt/app/app/wsgi.py'. [wsgi:error] [remote 192.168.3.110:37296] mod_wsgi (pid=25232): Failed to exec Python script file '/opt/app/app/wsgi.py'. [wsgi:error] [remote 192.168.3.110:37296] mod_wsgi (pid=25232): Exception occurred processing WSGI script '/opt/app/app/wsgi.py'. [wsgi:error] Traceback (most recent call last): [wsgi:error] File "/opt/app/app/wsgi.py", line 13, in <module> [wsgi:error] from django.core.wsgi import get_wsgi_application [wsgi:error] File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 1, … -
How to use select_related or prefetch_related with @property?
I have a model with a custom property: class Product(models.Model): name = models.CharField(_('Name'), max_length=255) [...] @property def price(self): return (self.price_line_product.filter(table__standard=True, table__client=self.client) .first().price) The price property will look in another table for the right data. price_line_product is the related_name to access it. It works fine but I have a lot of SQL queries that are executed. I tried in my view to add prefetch_related: Product.objects.filter(deleted=False).prefetch_related('price_line_product') Django doesn't return any error but it doesn't change the number of requests. How to force the ORM not to make duplicate requests? -
Django Model - How to set up ManytoMany, foreign key relation
I am trying to create a model, where an individual can have multiple roles in multiple firms. like a firm can assign an individual to Director and MD Roles, as well as Director role can be given to two separate individuals. an individual can have multiple roles in multiple Firms like MD in FirmA and Directors & MD in FirmB. I have three models, Firm, Individual and FirmRole. How can I achieve this? -
How To save Pdf to Excel file in Django
I have a Doubt How to save pdf file to Excel File : Here My Code Is : I Have Pdf File Need to Extract Some text In The Pdf File to Excel , What Actually I needed Is Need to Upload Pdf File in Template And Download , Need to Render the Pdf File And Save Into My Database And Retrieve To Next template As Download File Here My Code Is : def index(request): if request.method == 'POST': form = MyfileUploadForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data['file_name'] the_files = form.cleaned_data['files_data'] print(the_files) my_dataframe = pd.DataFrame() with pdfplumber.open(the_files) as pdf: for page in pdf.pages: text = page.extract_text().splitlines() nameIdx, add1Idx, add2Idx, add3Idx, ShipmentIdx, WaybillIdx, phoneIdx = -1, -1, -1, -1, -1, -1, -1 print('vikram2') for idx, line in enumerate(text): if "Shipment Reference :" in line: ShipmentIdx = idx if "Waybill Number : " in line: WaybillIdx = idx if "Invoice Number :" in line: nameIdx = idx - 1 if "Receiver :" in line: add1Idx = idx + 4 if "Receiver :" in line: add2Idx = idx + 6 if "Receiver :" in line: add3Idx = idx + 7 if "Tax ID :" in line: phoneIdx = idx - 1 textIdx = … -
Wrong SQL is generated when querying Array of Datetime field in Django
I have a model where I am storing datetime in Array Field. Now when I am using this Array field in F expression this is giving me SQL error. On Printing the SQL I can see that wrong SQL is being Generated. Here is the Sample MOdel Structure : class MyModel(models.Model): valid_date = models.DateTimeField(default=timezone.now) exclude_dates = ArrayField( models.DateTimeField(_("Exclude dates"), null=True, blank=True), null=True, blank=True ) Now When I will query this model to give me all records but ignore those Dates who are in exclude_dates list. qs = MyModel.objects.exclude(valid_date__range=F('exclude_dates')) This above ORM will raise psycopg2.errors.SyntaxError. if you will check resultant SQL by print(qs.query). You will find out that wrong SQL is being generated somehow. I am struggling to find out the reason of same and not able to think about the alternative solution. -
How to save csv file in django model?
This my model class CSV(models.Model): name = models.CharField(max_length=50, blank=True, null=True) height = models.CharField(max_length=50, blank=True, null=True) mass = models.CharField(max_length=50, blank=True, null=True) hair_color = models.CharField(max_length=50, blank=True, null=True) skin_color = models.CharField(max_length=50, blank=True, null=True) eye_color = models.CharField(max_length=50, blank=True, null=True) birth_year = models.CharField(max_length=10, blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) homeworld = models.CharField(max_length=255, blank=True, null=True) films = models.CharField(max_length=255, blank=True, null=True) species = models.CharField(max_length=255, blank=True, null=True) vehicles = models.CharField(max_length=255, blank=True, null=True) starships = models.CharField(max_length=255, blank=True, null=True) created = models.DateTimeField(auto_now_add=True, blank=True, null=True) edited = models.DateTimeField(auto_now_add=True, blank=True, null=True) url = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.name This my serializers from rest_framework import serializers class FileUploadSerializer(serializers.Serializer): file = serializers.FileField() class SaveFileSerializer(serializers.Serializer): class Meta: model = CSV fields = "__all__" This my view count = {'count': 0, "next_page": 1, 'dates': [],} starwars = [count, ] class PeopleView(generics.ListCreateAPIView): serializer_class = FileUploadSerializer def get(self, request): page = request.query_params.get('page', 1) if starwars[0]['next_page'] == int(page): url = f'https://swapi.dev/api/people/?page={page}' response = requests.get(url).json() starwars.append(response['results']) starwars[0]['count'] += 10 starwars[0]['next_page'] += 1 starwars[0]['dates'].append(datetime.today()) with open('story.csv', 'w', encoding='utf-8') as file: file.write(str(starwars[0])) file.write('\n') #csv.DictReader(file, delimiter=';') for i in range(1, len(starwars)): for j in starwars[i]: file.write(str(j)) file.write('\n') return Response(starwars, status=status.HTTP_200_OK) return Response({"error": "Enter valid page"}) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] reader = pd.read_csv(file, … -
How to wait in django until a request for endpoint arrives?
Tell me with what you can wait for a response to another endpoint? I am on the main page (index), entering something into the form. The POST request is sent to another server. At this moment: another server processes the data and, depending on their correctness, makes a POST request to my url /answer (True or False). I will be redirected, for example, to another page. How to register the logic of another page (another) so that Django waits for a POST request from another server to /answer and depending on this request True/False, I output everything OK or everything Bad on this page? url.py urlpatterns = [ path('index/', index, name='index'), path('page_2/', page_2, name='page_2'), path('answer/', answer, name='answer'), ] ------------------------------------------------- views.py def index(request): requests.post(example.com, data='My data') return redirect('page_2') def page_2(request): # wait request in answer if request.session['answer'] is True: return 'Ok' retunr 'Bad' def answer(request): data = request.data # send to page_2 or save in request.session['answer'] return Response(status=200) -
Django Admin CSS is not working as it should
I did run the python manage.py collectstatic code, and after that all the static files were collected in the static folder. but the static files needed for the syling of the admin panel are not working. Could you help? settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ 'Portfolio/static/', 'Portfolio/', '' ] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') -
Hiding exact location of classes and functions in a Django app (similar to how __init__.py works)
I have a Django app with this hierarchy: app_name ├── __init__.py ├── directory │ ├── one.py │ └── two.py ├── views.py │ ... In one.py I have a class called One and in two.py a class called Two. In order to import these classes in other apps, I have to write these two lines: from app_name.directory.one import One from app_name.directory.two import Two But I wish to change it so that I can import them like this: from app_name import One, Two In Python, I could just write these in __init__.py: from app_name.directory.one import One from app_name.directory.two import Two And that would work just fine. But in a Django app, this causes Django to raise this error: "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." In this answer, hspandher says, Also ensure that you are not importing models or similar app code, in init.py files of your apps. And in a comment, Well, ideally that's what "init_" is for to add public imports of the module. However, in case of Django apps, it also has tendency to cause circular imports and premature model imports because init file is parsed when an app is imported Okay, but how can it be done in Django? -
cross website login two different domain?
I have a doubt for the cross website login. one website made by php and anothe website is made by python django. how to connect these two websites? cross web site login these website are different domain . one website is done in php and codeigniter . then another website is done in python django website. if i login through php website . That php website navigation bar have one menu is login into the django website . Need to login same user in the django click. in the one click need to done for this. Please help me. whta kind of method in the cross login?. Please mention me and attach any links and any tutorials share with me -
Collectstatic deleting wagtail blog images
I have a wagtail site that I deploy using elasticbeanstalk. When I deploy collectstatic is ran: .platform/hooks/postdeploy #!/bin/sh source /var/app/venv/staging-LQM1lest/bin/activate python /var/app/current/manage.py migrate python /var/app/current/manage.py createsu python /var/app/current/manage.py collectstatic --noinput I have found that this has the effect of deleting any images that are in my blog posts. I assume this is because the blog posts have been made using the page editor (of the deployed site) and are not on my local machine like the rest of the static files How should I be setting things so that I do not delete the images everytime collectstatic is ran? -
Add extra HTML markup to features in Wagtail RichTextField editor?
How can I add extra HTML markup to individual features in Wagtail's RichTextField and have it be stored in the database? Specifically, I need to change the default appearance of a rendered <ul> list, so it would use custom font icons instead of bullet points. So instead of a <ul> list like this: <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> It would save the following in the database: <ul> <li><i class="bx bx-chevron-right">Item 1</li> <li><i class="bx bx-chevron-right">Item 2</li> <li><i class="bx bx-chevron-right">Item 3</li> <li><i class="bx bx-chevron-right">Item 4</li> </ul> Is that possible? -
How to upload random pictures from a list of array of pictures (which is a folder i have turned into an a list using **listdir** )folder to database
i want to upload random pictures from a static named folder to my database. These are my files. Please suggest a way. I am stuck here forever. views.py class VerifyOTPView(APIView): permission_classes = (AllowAny,) serializer_class = VerifyOTPSerializer def post(self, request): serializer = VerifyOTPSerializer(data=request.data) mobile = request.data['mobile'] otp_sent = request.data['otp'] #print('one_time_password', one_time) if mobile and otp_sent: old = Profile.objects.filter(mobile = mobile) if old is not None: old = old.first() otp = old.otp if str(otp) == str(otp_sent): serializer = self.serializer_class(data=request.data) mobile = request.data['mobile'] if serializer.is_valid(raise_exception=True): instance = serializer.save() content = {'mobile': instance.mobile, 'otp': instance.otp, 'name':instance.name, 'username':instance.username, 'logo':instance.logo, 'profile_id': instance.profile_id } return Response(content, status=status.HTTP_201_CREATED) else: return Response({ 'status' : False, 'detail' : 'OTP incorrect, please try again' }) serializers.py class VerifyOTPSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['mobile','otp'] def create(self,validated_data): instance = self.Meta.model(**validated_data) mywords = "123456789" res = "expert@" + str(''.join(random.choices(mywords,k = 6))) path = os.path.join(BASE_DIR, 'static') random_logo = random.choice([ x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x))]) instance = self.Meta.model.objects.update_or_create(**validated_data, defaults = dict( username = res, name = instance.mobile, logo = random_logo, profile_id = res))[0] instance.save() return instance models.py class Profile(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) logo = models.ImageField(upload_to ='profile/', blank=True,null = True) profile_id = … -
Inner join not working when serializing data
Similar questions has been asked before but I cannot use any of the answers to my case. Desired (SQL) query: SELECT project.name, invitation.* FROM invitation INNER JOIN project ON invitation.project_id_id=project.id; Models: class project(models.Model): project_code = models.CharField(max_length=250, null=False, blank=False) internal_code = models.CharField(max_length=250, null=True, blank=True, unique=True) name = models.CharField(max_length=250, null=False, blank=False) class invitation(models.Model): project_id = models.ForeignKey( project, on_delete=models.CASCADE ) country = models.CharField( max_length=250, null=False, blank=False, ) Desired result after the query: project.name invitation.project_id invitation.country Project_1 1 Madagascar Project_2 2 Laos View: def search(request): if request.method == 'GET': result = invitation.objects.select_related('project_id') data = serialize("json", result, cls=DatetimeJSONEncoder) return HttpResponse(data, content_type="application/json") return HttpResponse('') Here I used select_related as suggested in many other SO questions, however, if I print data (already serialized), there are no fields from the project model. The inner join is not working, I did something wrong. print(data): [{"model": "app_name.invitation", "pk": 19, "fields": {"project_id": 1, "country": "Madagascar"}}, {"model": "app_name.invitation", "pk": 20, "fields": {"project_id": 2, "country": "Laos"}}] print(str(result.query)) SELECT "app_name_invitation"."id", "app_name_invitation"."project_id_id", "app_name_invitation"."country", "app_name_project"."name" FROM "app_name_invitation" INNER JOIN "app_name_project" ON ("app_name_invitation"."project_id_id" = "app_name_project"."id") Why project.name is missing in the serialized data? -
How to check data of POST/PUT api method in Flask
data = request.get_json(force=True) print(data) emp = Employee.query.get(employee_id_to_update) print(emp.name) print(set(data.keys())) if 'dm' in data.keys() and logged_user.designation.lower() != "hr": return jsonify("You cannot perform this action") if data.get('name') : emp.name=data\['name'\] if data.get('email'): emp.name = data\['email'\] if data.get('gender'): emp.name = data\['gender'\] I have tried this but i dont want multiple if statements , is there any way to replace if else statements -
Django - using HTMX, what character is posted/inserted when I tab across cells in a table?
I have a table and within the table is a form. Each cell in the table has an input tag and displays an object. This object can be modified directly because I am using htmx to detect a keyup in each cell. My view takes the post data every time htmx is triggered and checks the data. If this data is not equal to one of the options for input, I don't save the object. Additionally, I change the cell border to the color red. This worked as expected. Next, I changed the code so that whitespace is removed from the post data. This also worked as expected. template <form action="" method="post" class="form-group"> {% for student in student_list %} <tr> {% for g in grade_list %} {% if g.student.id == student.id %} <td> <input type="text" hx-post="{% url 'gradebook:grade-change' g.pk %}" hx-swap="outerHTML" hx-trigger="keyup delay:1200ms" class="form-control score" title={{ g.score }} name="score" id="input-{{ forloop.counter0 }}" placeholder={{ g.score }} required> </td> {% endif %} {% endfor %} </tr> {% endfor %} </form> view def post(self, request, *args, **kwargs): grade = self.get_object() user = grade.user ns = request.POST.get('score') new_score = ns.upper() print(new_score) # remove whitespace and tabs new_score = re.sub(r"[\n\t\s]*", "", new_score) score_list = ["EXT", … -
Guidance Needed … [closed]
I have learned python well in the last 3 months and a little bit of Django with it. Currently I am confused a lot that weather I should proceed with learning frontend and Django well or should I start learning Data Structures and Algorithms. As want to go into development. Please help me out with it... I just want guidance and support as I am confused a lot. -
nginx svelte django(waitress) external ip no response
'nginx.conf' server { listen 8888; server_name xxx.xx.xxx.xx; // my PC's external ip root html; } and i running django server by waitress in xxx.xx.xxx.xx:8072 this is my svelte code fetching django server const res = await fetch(http://xxx.xx.xxx.xx:8072/myapp/); so build this svelte app and copy public folder's component to nginx/html and run nginx, 'http://xxx.xx.xxx.xx:8888/myapp' no respond in django server however, if the fetching code is 'localhost:8072' and django server with locahost:8072, nginx server_name -> 'localhost', this work properly why nginx has no response for external ip? Sorry for my poor English. -
Need help to getting setup google login using Django rest framework plus React Js
views class GoogleCreateAccount(APIView): permission_classes = [permissions.AllowAny] def post(self, request): reg_serializer = RegisterSerializer(data=request.data) if reg_serializer.is_valid(): new_user = reg_serializer.save() if new_user: # add these r = requests.post('http://127.0.0.1:8000/auth/token', data={ 'username': new_user.email, 'id_token': request.data['code'], #'password': request.data['password'], 'client_id': '304129974707-79jslq7l318va16eacni8cveokn237g8.apps.googleusercontent.com', 'client_secret': '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', 'grant_type': 'id_token' }) return Response(r.json(), status=status.HTTP_201_CREATED) return Response(reg_serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py urlpatterns = [ path('auth/', include('drf_social_oauth2.urls',namespace='drf')), path('googleregister/',GoogleCreateAccount.as_view()), ] I was setting up an google login with django and react app i was setting it up based on the https://abhik-b.medium.com/step-by-step-guide-to-email-social-logins-in-django-5e5436e20591 above link. It is working on the bcakend as expected. But for getting the access token the parameters I giving is { clientid: client secret: grant type: password username: password: } But in the react it couldnt able to get the password parameter so it is not getting connected to the rest api call. I dont know exactly how to get this issue sorted. Please suggest me a best link or docs for setting up google login for django rest framework as backend and react js as frontend. And is this possible to change the grant type to authorisation code and if so what needs to be changed? -
Why django timezone offset is different?
Djanfo 3.2.10, python 3.9 settings.py TIME_ZONE = 'Europe/Moscow' script.py from django.utils import timezone tzinfo = timezone.localtime().tzinfo # <class 'pytz.tzfile.Europe/Moscow'> tz = timezone.get_current_timezone() # <class 'pytz.tzfile.Europe/Moscow'> dtz = timezone.get_default_timezone() # <class 'pytz.tzfile.Europe/Moscow'> datetime_object = timezone.now() print(datetime_object) # 2022-03-29 03:34:42.244830+00:00 print(datetime_object.replace(tzinfo=tzinfo)) # 2022-03-29 03:34:42.244830+03:00 print(datetime_object.replace(tzinfo=tz)) # 2022-03-29 03:34:42.244830+02:30 print(datetime_object.replace(tzinfo=dtz)) # 2022-03-29 03:34:42.244830+02:30 +0230 is not +0300 What is it?) Correct offset for this timezone is +0300. -
how to input array in django html
I am new to django. I want to make a website to change tables in a database. It should be implemented change, deletion, addition of a note. The problem is that one of the parameters of the Array table and I don't know how to make it input. I tried to do it through text input but it didn't work for me Here my code forms.py from .models import dj_ksg_p from django.forms import ModelForm, TextInput class KSGForms(ModelForm): class Meta: model=dj_ksg_p fields=['id','name','c_prof','smj_prof','KSG'] widgets={ "id": TextInput(attrs={ 'class':'from-control', 'placeholder':'Id' }), "name": TextInput(attrs={ 'class': 'from-control', 'placeholder': 'Название МО' }), "c_prof": TextInput(attrs={ 'class': 'from-control', 'placeholder': 'Профиль' }), "smj_prof": TextInput(attrs={ 'class': 'from-control', 'placeholder': 'Смежный профиль' }), "KSG": TextInput(attrs={ 'class': 'from-control', 'placeholder': 'КСГ' }) } views.py from django.shortcuts import render,redirect from django.views.generic.list import ListView from django.views.generic import DetailView, UpdateView,DeleteView from django.http import HttpResponse from .models import dj_ksg_p from rest_framework import viewsets from .forms import KSGForms \#from .serializers import HeroSerializer class KSGView(ListView): model = dj_ksg_p template_name = 'ksg/kss.html' queryset = dj_ksg_p.objects.all() class NewDataView(DetailView): model = dj_ksg_p template_name = 'ksg/create.html' context_object_name = 'dj_ksg_p' class DeleteKSG(DeleteView): model = dj_ksg_p template_name = 'ksg/delete.html' success_url = '/ksg/' class NewUpdateView(UpdateView): model=dj_ksg_p template_name = 'ksg/detail_view.html' fields = \['id','name','c_prof','smj_prof','KSG'\] form_class=dj_ksg_p def create(request): error = '' … -
Password Reset Custom Email Validation Message Django with MongoDB
I can successfully send an email for a password reset. But when the email address is invalid, the password reset email request has been sent. I don't know how I can check whether the email address is valid or invalid. When the email address is valid, the email will be sent, and when the email address is invalid, an error message will be displayed in the password reset form. I have found similar problems on Stackoverflow. But it didn't work for me. Password Reset Custom Validation Message Inform user that email is invalid using Django's Password Reset Here is my code: In forms.py class EmailValidationOnForgotPassword(PasswordResetForm): def clean_email(self): email = self.cleaned_data['email'] if not User.objects.filter(email__iexact=email, is_active=True).exists(): raise forms.ValidationError("Invalid Email address.") return email In urls.py urlpatterns = [ path('password_reset/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset.html"), name="password_reset"), path('password_reset/', auth_views.PasswordResetView.as_view(form_class=EmailValidationOnForgotPassword), name='password_reset'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="registration/password_reset_done.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="registration/password_reset_confirm.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="registration/password_reset_complete.html"), name="password_reset_complete"), ] Environment version: Django==4.0.2 djongo==1.3.6 sqlparse==0.2.4 Can anyone please help me? I need this fix as soon as possible.