7

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?

Stuart Axon
  • 1,844
  • 1
  • 26
  • 44

2 Answers2

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)
jTiKey
  • 696
  • 5
  • 13
ojii
  • 4,729
  • 2
  • 23
  • 34
  • 1
    If 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
  • 6
    Note 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
  • 5
    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'``` – 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