Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make calculation inside django annotate?
This one when I run generates error: qs = UserLocation.objects.annotate(distance=0.5 - cos((F('lat')-lat1)*p)/2 + cos(lat1*p) * cos(F('lat')*p) * (1-cos((F('long')-lon1)*p))/2).all() The error it generates is this one: must be real number, not CombinedExpression How can I make that calculation as an annotation -
Django.request is not showing synchronous middleware as docs suggest
I've set up a very simple asynchronous view but it's not working. As per the Django instructions I want to check that it's not my middleware causing the issue. The Django docs say that the django.request logger will disclose which middleware is not working in async. Below is the quote from the official docs. I've set up the django.request logger and it logs an 4xx or 5xx errors (as expected) but that's all. Is this a mistake in the Django docs? https://docs.djangoproject.com/en/4.0/topics/async/ You will only get the benefits of a fully-asynchronous request stack if you have no synchronous middleware loaded into your site. If there is a piece of synchronous middleware, then Django must use a thread per request to safely emulate a synchronous environment for it. Middleware can be built to support both sync and async contexts. Some of Django’s middleware is built like this, but not all. To see what middleware Django has to adapt, you can turn on debug logging for the django.request logger and look for log messages about “Synchronous middleware … adapted”. settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', … -
What is the most efficient way for calculating SLA?
I am trying to figure out how can I improve my code. So basicaly there is a website and there are some events which user can do it. We are giving some summary about event result to user and SLA is one of them. If I want to calculate event SLA, I can do it by retrieving the object and subtracting start_time from end_time. Related Model: class Event(models.Model): ... start_time = models.DateTimeField() end_time = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) ... My code for calculating SLA is below. events = Event.objects.all() tmp_sla = 0 for event in events: time_difference = event.end_time - event.start_time tmp_sla += time_difference // 60 # convert seconds to minute average_sla = tmp_sla // events.count() The problem is there are so many events and many users. This is causing long calculating time. And sometimes I need to use more than one for loop to calculate it. Calculation time taking even longer. Is there any built-in Django function for this? Or how can I improve my codes? Thanks in advance. -
pytest -rP logs twice for each test
I'm building a test suite for a small Django app and am using pytest. When I run the tests with docker-composec -f local.yml run --rm django pytest -rP, it logs each test twice. I added a timestamp to the function being tested (2022-02-20 20:57:32.196975+00:00) and they are identical so I don't think its running the tests twice, but outputting them twice. _______________________________________________________________________________________________________ TestAggregateTiltReadings.test_initial_run _______________________________________________________________________________________________________ ------------------------------------------------------------------------------------------------------------------ Captured stderr call ------------------------------------------------------------------------------------------------------------------ INFO 2022-02-20 20:57:32,196 services 1 140188905805632 2022-02-20 20:57:32.196975+00:00 INFO 2022-02-20 20:57:32,197 services 1 140188905805632 Aggregating 4 new tilt readings ------------------------------------------------------------------------------------------------------------------- Captured log call -------------------------------------------------------------------------------------------------------------------- INFO brew_dash.tilts.services:services.py:33 2022-02-20 20:57:32.196975+00:00 INFO brew_dash.tilts.services:services.py:34 Aggregating 4 new tilt readings _______________________________________________________________________________________________________ TestAggregateTiltReadings.test_initial_run _______________________________________________________________________________________________________ ------------------------------------------------------------------------------------------------------------------ Captured stderr call ------------------------------------------------------------------------------------------------------------------ INFO 2022-02-20 20:57:32,196 services 1 140188905805632 2022-02-20 20:57:32.196975+00:00 INFO 2022-02-20 20:57:32,197 services 1 140188905805632 Aggregating 4 new tilt readings ------------------------------------------------------------------------------------------------------------------- Captured log call -------------------------------------------------------------------------------------------------------------------- INFO brew_dash.tilts.services:services.py:33 2022-02-20 20:57:32.196975+00:00 INFO brew_dash.tilts.services:services.py:34 Aggregating 4 new tilt readings I used cookiecutter-django to start the app and am using the default settings. I'm not sure what configs to share which might be helpful to troubleshoot this. I can add some if there are any ideas. -
How to deploy django, reactjs with oracle 19c in google cloud platform compute engine vm cpanel image?
I am newbie in cpanel. I have developed a webapp with django, reactjs with oracle 19c. This is running smothly in windows 10 local machine. Now i want to use it google cloud platform compute engine with vm cpanel image. Is it possible? Or please suggest me that how does i will run this smoothly. Thanks in advance. -
django serializer field not recognizing attribute clearly defined
when i try to run a view I get this error: AttributeError: Got AttributeError when attempting to get a value for field `inreplytouser` on serializer `ContentFeedPostCommentSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'inreplytouser'. Here is my model: class ContentFeedPostComments(models.Model): inreplytouser = models.ForeignKey(SiteUsers, null=True, related_name='replytouser', blank=True, on_delete=models.CASCADE) inreplytotopcomment = models.BigIntegerField(null=True, blank=True) timecommented = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(SiteUsers, on_delete=models.CASCADE) contentcreator = models.ForeignKey(ContentCreatorUsers, on_delete=models.CASCADE) contentfeedpost = models.ForeignKey(ContentFeedPost, on_delete=models.CASCADE) text = models.CharField(max_length=1000) here is the serializer: class ContentFeedPostCommentSerializer(ModelSerializer): id = IntegerField() inreplytouser = SiteusersSerializer() user = SiteusersSerializer() contentcreator = ContentCreatorSerializer() class Meta: model = ContentFeedPostComments fields = ('id','inreplytouser', 'inreplytotopcomment', 'timecommented', 'user', 'contentcreator', 'contentfeedpost', 'text') here is the view: class ContentFeedPostsComments(APIView): def get(self, request, *args, **kwargs): postid = kwargs.get('postid') contentfeedpost = get_object_or_404(ContentFeedPost, id=postid) topcomments = ContentFeedPostComments.objects.filter(contentfeedpost= contentfeedpost, inreplytotopcomment= None).order_by('timecommented') replycomments = ContentFeedPostComments.objects.filter( contentfeedpost = contentfeedpost, inreplytotopcomment__isnull = False).order_by('timecommented') serializedtopcomments = ContentFeedPostCommentSerializer(topcomments) serializedreplycomments = ContentFeedPostCommentSerializer(replycomments) payload = { 'topcomments': serializedtopcomments.data, 'replycomments': serializedreplycomments.data } return Response(payload) I was reading something about source being passsed into the inreplytouser field of the serializer field but that makes no sense. Your wisdom and knowledge on this situation is greatly … -
Django: Unresolved reference, when trying to import an app
I am having issues with importing other apps and could not find a solution on the internet. I get an Unresolved reference 'name'. Project/urls.py from django.contrib import admin from django.urls import path,include from users import views as user_views #'users' and 'views' are underlined in red from homepage import views as homepage_views #same goes for 'homepage' and 'views' urlpatterns = [ path('',include("homepage.urls")), path('register/',user_views.register), path('admin/', admin.site.urls), ] Project/settings.py INSTALLED_APPS = [ 'homepage.apps.HomepageConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Project Structure Project structure Thanks for your help and let me know if u need more information -
Default date won't set mock date when saving instance
There is an issue mocking the date.today() method when create an instance of the Question model through a ModelForm. The default date that is stored with the instance is date(2022, 2, 20) when it should be date(2021, 12, 9). The import path of the object to patch is "posts.models.date" and models.py in fact has the import statement from datetime import date. What needs to be changed in order for the date to be mocked properly where the instance has the date as defined in the testcase? posts.test.test_forms.py from datetime import date from unittest.mock import Mock, patch class TestDuplicateQuestionPosted(TestCase): '''Verify that a User cannot post two questions with the exact same title in the same day.''' @classmethod def setUpTestData(cls): user = get_user_model().objects.create_user("TestUser") cls.profile = Profile.objects.create(user=user) cls.question = Question.objects.create( title="Question Title 001", date=date(2021, 12, 9), body="This is the extra content about my post: Question__0001", profile=cls.profile ) print(Question.objects.all()) def test_duplicate_question_posted_on_same_day(self): with patch("posts.models.date") as mock_date: mock_date.today = date(2021, 12, 9) data = { 'title': "Question Title 001", "body": "This is the extra content about my post: Question__0001", "profile": self.profile } form = QuestionForm(data) self.assertFalse(form.is_valid()) self.assertTrue(form.has_error("title")) self.assertEqual( form.errors.as_data()['title'][0].message, "Cannot post duplicate question" ) posts.models.py from datetime import date class Post(Model): date = DateField(default=date.today) comment = … -
Getting data from plain HTML form into Django User object
I have created my own plain HTML form and I want to get that data into a view to create the default User object. However , I am not being able to get the data from the form, here is my view : def registerPage(request): if request.method == "POST": print(request.POST.get('name')) print(request.POST.get('useremail')) username = request.POST.get('name') email = request.POST.get('useremail') password = request.POST.get('userpassword') user = User.objects.create_user(username, email, password) return HttpResponse("Printed to the console") else: return render(request, 'store/register.html') The console prints "None" as a result. This the HTML : <form class="mx-1 mx-md-4" method="POST" action="http://127.0.0.1:8000/register"> {% csrf_token %} <div class="d-flex flex-row align-items-center mb-4"> <i class="fas fa-user fa-lg me-3 fa-fw"></i> <div class="form-outline flex-fill mb-0"> <input type="text" id="name" class="form-control" /> <label class="form-label" for="name">Your Name</label> </div> </div> <div class="d-flex flex-row align-items-center mb-4"> <i class="fas fa-envelope fa-lg me-3 fa-fw"></i> <div class="form-outline flex-fill mb-0"> <input type="email" id="useremail" class="form-control" /> <label class="form-label" for="useremail">Your Email</label> </div> </div> <div class="d-flex flex-row align-items-center mb-4"> <i class="fas fa-lock fa-lg me-3 fa-fw"></i> <div class="form-outline flex-fill mb-0"> <input type="password" id="userpassword" class="form-control" /> <label class="form-label" for="userpassword">Password</label> </div> </div> <div class="d-flex flex-row align-items-center mb-4"> <i class="fas fa-key fa-lg me-3 fa-fw"></i> <div class="form-outline flex-fill mb-0"> <input type="password" id="form3Example4cd" class="form-control" /> <label class="form-label" for="form3Example4cd">Repeat your password</label> </div> </div> <div class="d-flex justify-content-center … -
Trouble when parsing JSON string
I'm dumping JSON in Django view and then parsing JSON in JS to get the data. My view.py (Django) ibms = [] for i in range(2, 5): ibm = Mapa(i, wsMapa) ibms.append(ibm.__dict__) ibms = json.dumps(ibms) return render(request, 'mapas/index.html', {'ibms': ibms}) The ibm variable output in Django template is: [{"numeroIbm": "AUTO P"}, {"numeroIbm": "PTB"}, {"numeroIbm": "FAROL"}] My index.html (JS inside) {{ ibms|json_script:"ibms" }} <script> const mydata = JSON.parse(document.getElementById("ibms").textContent); const mydata2 = JSON.parse(mydata); </script> The issue is: I'm having to JSON.parse double times to get the JS object. The variable mydata, despite the JSON.parse, is string typeof. I only get the final result when I JSON.parse for the second time (mydata2). What is happening, pls? Tks in advance! -
build an application with django and a data warehouse
I'm working on a Django application but I don't know how to integrate a data warehouse with Django. in fact is it possible to do this idea? -
In Django, ModelAdmin, what is the difference between save_form() and save_formset()?
Can somebody explain the differences and/or similarities between save_form and save_formset from ModelAdmin? The only things i could find about this is from source code. def save_form(self, request, form, change): """ Given a ModelForm return an unsaved instance. ``change`` is True if the object is being changed, and False if it's being added. """ return form.save(commit=False) def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """ formset.save() And the docs have only this about save_formset (https://docs.djangoproject.com/en/4.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_formset) The save_formset method is given the HttpRequest, the parent ModelForm instance and a boolean value based on whether it is adding or changing the parent object. -
How to implement all CRUD methods in a single Class Based View in Django framework
Good day everyone. After countless attempts to solve my problem, I decided to turn here for advice. I am writing a small app with two models: Departments and Employees. And I decided to rewrite all the Function-Based Views to Class-Based Views. With Django REST framework I was able to implement the following solution: That is drf-api-view.py: from django.core.cache import cache from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.exceptions import ValidationError from rest_framework.pagination import LimitOffsetPagination from django_filters.rest_framework import DjangoFilterBackend from department.models.models import Department, Employee from department.rest.serializers import DepartmentSerializer, EmployeeSerializer class DepartmentPagination(LimitOffsetPagination): default_limit = 10 max_limit = 100 class EmployeePagination(LimitOffsetPagination): default_limit = 10 max_limit = 100 class DepartmentView(ListAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView): queryset = Department.objects.all().order_by('title') serializer_class = DepartmentSerializer filter_backends = (DjangoFilterBackend,) pagination_class = DepartmentPagination lookup_field = 'id' def list(self, request, *args, **kwargs): if isinstance(request.resolver_match.kwargs.get('id', None), int): return super().retrieve(request, *args, **kwargs) return super().list(request) def create(self, request, *args, **kwargs): title = request.data.get('title') if title is None: raise ValidationError({'title': 'Must not be empty'}) return super().create(request, *args, **kwargs) def update(self, request, *args, **kwargs): response = super().update(request, *args, **kwargs) if response.status_code == 200: department = response.data department_id = department['id'] cache.set(f'department_data_{department_id}', { 'title': department['title'], 'slug': department['slug'], }) return response def delete(self, request, *args, **kwargs): department_id = request.data.get('id') response = super().delete(request, … -
TypeError: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x7f5e95756920>
first time I ask on the website. I was testing a Django Restframework app. The is to check an unauthenticated user that wants to create a review. I got this error: TypeError: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x7f5e95756920>. this is the class test: class ReviewTestCase(APITestCase): def setUp(self): self.user = User.objects.create_user( username="example", password="Password@123") self.token = Token.objects.get(user__username=self.user) self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) self.stream = models.StreamPlatform.objects.create( name="Netflix", about="#1 Platform", website="https://www.netflix.com" ) self.watchlist = models.WatchList.objects.create( platform=self.stream, title="Example Movie", storyline="Example Movie", active=True ) self.watchlist2 = models.WatchList.objects.create(platform=self.stream, title="Example Movie", storyline="Example Movie", active=True) self.review = models.Review.objects.create(review_user=self.user, rating=5, description="Great Movie", watchlist=self.watchlist2, active=True) def test_review_create(self): data = { "review_user": self.user, "rating": 5, "description": "Great Movie!", "watchlist": self.watchlist, "active": True } response = self.client.post( reverse('reviewcreate', args=(self.watchlist.id,)), data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(models.Review.objects.count(), 2) response = self.client.post( reverse('reviewcreate', args=(self.watchlist.id,)), data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) **#The test who cause the error** def test_review_create_unauth(self): data = { "review_user": self.user, "rating": 5, "description": "Great Movie!", "watchlist": self.watchlist, "active": True } self.client.force_authenticate(user=None, token=None) response = self.client.post( reverse('reviewcreate', args=(self.watchlist.id,)), data) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_review_update(self): data = { "review_user": self.user, "rating": 4, "description": "Great Movie! - Updated", "watchlist": self.watchlist, "active": False } response = self.client.put( reverse('review-detail', args=(self.review.id,)), data) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_review_list(self): response = self.client.get( reverse('movie-review', args=(self.watchlist.id,))) … -
html iterate through dictionary python in django
i trying to use defaultlist but it is not working in my Django app views.py: Mylist = defaultdict(list) Mylist["it is a girl "].append(room_id) Mylist["it is a boy"].append(name_id) .html: {% for key, value in mylist.items %} <tr> <td> Key: {{ key }} </td> <td> Value: {{ value }} </td> </tr> {% endfor %} what is wrong? -
Convert raw sql query to django orm
I written this query in PostgreSQL and I'm confused of conversion of this query to django orm SELECT count(*), concat(date_part('month', issue_date), '/', date_part('year', issue_date) ) as date FROM affiliates_issuelog WHERE tenant_id = '{tenant_id}' GROUP BY date_part('month', issue_date), date_part('year', issue_date) ORDER BY date_part('year', issue_date) desc, date_part('month', issue_date) desc I have this model that records the insertion of new affiliates by date and by institution (tenant), only I need to receive from the query the total amount of records inserted per month in the year, and I was using the listview to make my pages until then but I don't know how to filter this data using orm. class IssueLog(): tenant = models.ForeignKey("tenants.Federation", on_delete=models.CASCADE) issue_date = models.DateField( default=date.today, verbose_name=_("date of issue") ) class Meta: abstract = True verbose_name = _("Entrada de emissão") verbose_name_plural = _("Entradas de emissão") def __str__(self): return f"{self.institution}, {self.tenant}" My pages that return a list of data I did as the example below, is it possible to pass the data as I want through get_queryset()?, I already managed to solve my problem using the raw query, but the project is being done only with orm so I wanted to keep that pattern for the sake of the team. Ex: … -
How to log Django request time?
How to display Django requests time in my console? For exemple: "GET /cities/ HTTP/1.1", I need time of this response. -
Django form for adding emails connected to models
This is a bit hard to explain but I'll try my best. I am developing a website where I want a feature where the admins can add an email notification connected to a certain model. The admin should be able to Choose a model on the website, What event it should trigger on (create, update or delete), The email body and text. For example, if the admin adds an email to a model foo on a create event, the specified email should be sent to some recipient whenever a new foo is added to the database. I am attempting to implement a new model that contains some reference to the models, using post_save() to send emails, but it's turning out more complex than I thought. I have searched far and wide to find some addon that does this, but I haven't found any. Does anyone have any tips on specific functionalities that can help with this, or if there's a good addon that I can start with? -
Adding two column values with F class in django failed
The three columns in question are num1, num2 and total. All I want is to add the value of num1 and num2 to get the total value and populate the total column with that value. I am getting no errors but nothing is updating. Simply the code is having no effect. Addbanks is the name of the model. Here is the one liner that seemed to be best suited for this purpose- Addbanks.objects.all().update(total=F('num1') + F('num2')) Update method worked like a charm for me till now. I am surprised that it is not working. I will add some pictures for you to see how simple the models and views.py is. If you have any tips or any other way to achieve what I am trying to, that would be helpful. Thnaks. Views.py- models.py- The table looks like this- -
how to fix attribute error while running python manage.py run server
[enter image description here] how to fix this error -
Django in Docker on Nginx request to self fails when in the context of another request
I have a Django application deployed inside a container on top of Nginx using Dokku. One of the view functions of the Django application includes a request: views.py def foo(request): ... response = requests.get(url) ... It is probably noteworthy that url is the url of the Django application itself, so the request is from the application to itself. The request is to one of the API endpoints (the reasons for doing this are historical). When the view is called then the request to url fails with 504 gateway timeout. I cannot reproduce this in any other context specifically: There is no error when running on localhost with the development server, where url is then the url of the development app (localhost to itself works). There is no error when running on localhost with the development server, where I manually make the url the production url (localhost to production works). There is no error when running this request on the production server but outside of the view. Specifically, I did a docker exec into the container, started the Django environment (manage.py shell), and ran the exact request that the view was making, and it worked! (production to production works) It seems … -
How to check input type Django Rest?
I am developing an endpoint with the Django rest framework. My endpoint accepts file or text. On the frontend side, users can send text or file. I am confused about how to check input is a file or text? I have tried os.path.is_file() but it does not check InMemoryUploadedFile. Can anybody help me with this issue? -
How to use NPM modules inside python?
I have a python django application. And I need to use some functions from an npm library in my django application. This is how the javascript code looks like: const { signLimitOrder } = require("@sorare/crypto"); return JSON.stringify(signLimitOrder(privateKey, limitOrder)) How do I use signLimitOrder function from my django python application? What is the standard procedure to solve this problem? Rewrite the JS library in Python Run a nodejs server and use API to pass data to Python app Is there a python package to run Js libraries inside python? Thanks -
displaying json data to django template
i am getting data from mongodb and first inserting all the data into pandas and then converting that data to json data and then print that data in table format my views.py looks like this def generate(request): a=str(request.POST.get('level')) b= request.POST.get('status') c=(request.POST.get('startdate')) g=datetime.strptime(c,"%Y-%d-%m") d=datetime.strftime(g,"%Y/%d/%m") e=request.POST.get('enddate') h=datetime.strptime(e,"%Y-%d-%m") f=datetime.strftime(h,"%Y/%d/%m") output=run([sys.executable,'C:\\Users\\siddhant\\Desktop\\intern mongo\\indicator\\work\\water.py',a,b,d,f],stdout=PIPE,text=True) client=pymongo.MongoClient("mongodb://localhost:27017") db = client["water"] colle= db["waterlevel"] df3=pd.DataFrame() df4=pd.DataFrame() data_from_db = colle.find({},{"_id":0,"time":1,"status":1,"level":1}) for datta in data_from_db: df=pd.DataFrame(datta) df4=pd.concat([df4, df], ignore_index=True,axis=0) json_records = df4.reset_index().to_json(orient='records',date_format='epoch') data = [] data = json.loads(json_records) context = {'d': data} return render(request,'result.html',context) and my html template is this <!DOCTYPE html> <html lang="en"> <head> <title>TableView - Startup</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2 class="text-center"><u>water table</u></h2><br> <table class="table table-dark table-striped"> <thead> <tr> <th>time</th> <th>status</th> <th>level</th> </tr> </thead> <tbody> <!-- jinja2 Technique --> {% if d %} {% now "U" %} {% for i in d %} <tr> <td>{{i.time|date:'U'}}</td> <td>{{i.status}}</td> <td>{{i.level}}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </div> </body> </html> the problem is I am getting DateTime in UNIX format I want it in readable date type format can someone suggest a better way to display pandas dataframe in Django template as a table other than … -
form rendering 'None' in production
When I use the password reset in development it works fine. However in production after the user opens the reset email the password reset form is not displayed however other forms on the site via crispy forms are working fine. Nothing has been changed from dev to production besides the url in the view. The server and dev are running the same version of crispy forms. I did it based off this tutorial and it seems I have made all the required changes for production When checking the urls of the email between production and dev i do not see an issue http://127.0.0.1:8000/reset/MQ/***hm*-e00d**b30b635b358be1573e********/ https://domain.co/reset/MQ/***ht*-71ff80c**580c6cecc3ffd44********/ If I try and render the form like {{ form }} it only renders None leading me to believe the context is not being passed view: def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(Q(email=data)|Q(username=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" plaintext = template.loader.get_template('users/password_reset_email.txt') htmltemp = template.loader.get_template('users/password_reset_email.html') c = { "email":user.email, 'domain':'domain.com', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'https', } text_content = plaintext.render(c) html_content = htmltemp.render(c) try: msg = EmailMultiAlternatives(subject, text_content, 'myemail@email.com', [user.email], headers = {'Reply-To': 'myemail@email.com'}) msg.attach_alternative(html_content, "text/html") msg.send() …