koddr
koddr

Reputation: 784

How to send password reset mail from custom Django views?

I have Django 2.0.2 with custom User model. One of feature is give anonymous users way to create order without "register-first" on site.

Main idea is:

This was killed two functions by one: user register and create first order.

And question: how can I send reset password mail from my custom views? I understand, link will generate and send on PasswordResetView view, but how to call to them on custom view?

Upvotes: 3

Views: 5520

Answers (1)

hwhite4
hwhite4

Reputation: 715

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="[email protected]", 
        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

Upvotes: 3

Related Questions