[Django]-How to send password reset mail from custom Django views?

3👍

To send the password reset link from a view you can fill out a PasswordResetForm which is what is used by the PasswordResetView
https://docs.djangoproject.com/en/2.0/topics/auth/default/#django.contrib.auth.forms.PasswordResetForm

As described in another stackoverflow answer here https://stackoverflow.com/a/30068895/9394660 the form can be filled like this:

from django.contrib.auth.forms import PasswordResetForm

form = PasswordResetForm({'email': user.email})

if form.is_valid():
    request = HttpRequest()
    request.META['SERVER_NAME'] = 'www.mydomain.com'
    request.META['SERVER_PORT'] = '443'
    form.save(
        request= request,
        use_https=True,
        from_email="username@gmail.com", 
        email_template_name='registration/password_reset_email.html')

Note: if you are not using https replace the port with 80 and dont include use_https=True

Also depending on the situation you may already have a request and wouldn’t need to create one

Leave a comment