I want to be able to send a password reset email using django.contrib.auth.views.password_reset but without using the browser - password_reset needs a populated form, is there a way I can create this programmatically and get the email sent?
Asked
Active
Viewed 6,004 times
7
-
1"without browser" / "not without a browser". What? – S.Lott Apr 08 '11 at 11:10
-
@S.Lott - Heh, question was terribly typed :) – Stuart Axon Nov 15 '12 at 13:15
2 Answers
15
from django.contrib.auth.forms import PasswordResetForm
def reset_password(email, from_email, template='registration/password_reset_email.html', domain_override="localhost:8000"):
"""
Reset the password for all (active) users with the given E-Mail address
"""
form = PasswordResetForm({'email': email})
if form.is_valid():
return form.save(from_email=from_email, email_template_name=template)
-
1If you get a redirection error then you need to add the template to your urls, as mentioned here: http://stackoverflow.com/questions/4790838/django-reset-password-confirm-templatesyntaxerror-problem – Stuart Axon Apr 08 '11 at 13:44
-
6Note that in more recent version of Django (not entirely sure starting from which), you need to call `form.is_valid()` before `form.save()` – Martin B. Mar 30 '15 at 13:03
-
If you are calling form.save() from a view you might also need to pass the request as one of the parameters... form.save(request=request, ...) – Dustfinger Dec 29 '16 at 18:08
-
5You may need to add a "domain_override" kwarg to save if you aren't sending "request". As in ```form.save(from_email=from_email, mail_template_name=template, domain_override="localhost:8000")``` This prevents the ```AttributeError: 'NoneType' object has no attribute 'get_host'``` – chaggy May 10 '18 at 21:58
-
It sends plain text for me, instead of HTML via email, am I missing something? – код е Apr 11 '22 at 22:04
6
You can just use django.contrib.auth.forms.PasswordResetForm and populate it with data like this:
form = PasswordResetForm({'email':'sample@sample.com'})
The sending of email is done upon save().

gladysbixly
- 2,591
- 18
- 15