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?
2 Answers
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)
5 Comments
Stuart Axon
If you get a redirection error then you need to add the template to your urls, as mentioned here: stackoverflow.com/questions/4790838/…
Martin B.
Note that in more recent version of Django (not entirely sure starting from which), you need to call
form.is_valid() before form.save()Dustfinger
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, ...)
chaggy
You 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'koro
It sends plain text for me, instead of HTML via email, am I missing something?
You can just use django.contrib.auth.forms.PasswordResetForm and populate it with data like this:
form = PasswordResetForm({'email':'[email protected]'})
The sending of email is done upon save().