Python – How do I send a password reset email from a custom Django View?

How do I send a password reset email from a custom Django View?… here is a solution to the problem.

How do I send a password reset email from a custom Django View?

I have Django 2.0.2 with a custom User model. One of the features is a way for anonymous users to create orders without having to “register first” on the website.

The main idea is:

  • Anonymous users fill out the order, enter an email address, and click Create Order;
  • Django creates users using the entered email and a randomly generated password;
  • Next, Django (or Celery) sends a link to reset your password to an email (similar to a standard reset form);
  • The user checks the email and clicks the reset link to re-enter their password.

This is killed by one by two functions: user registration and creation of the first order.

And the question: How do I send a reset password email from my custom View? I know, links will be generated and sent on the PasswordResetView View, but how do I call them on a custom View?

Solution

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

As described in another StackOverFlow answer here< a href="https://stackoverflow.com/a/30068895/9394660" rel="noreferrer noopener nofollow" >https://stackoverflow.com/a/30068895/9394660 The form can be filled out 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 do not use https, replace the port with 80 and do not include use_https=True

Also, depending on the situation, you may already have a request and do not need to create one

Related Problems and Solutions