For this short tutorial we will be using the django.contrib.auth
views to add a password reset functionality to your
Django application. The process of reseting passwords involves sending emails. For that matter we will be using console
email backend to debug and check if everything is working. In the end of this tutorial I will also provide resources
to properly configure a prodution-quality email server.
Dependencies
Basically all you need is to have django.contrib.auth
in your INSTALLED_APPS
and a email service properly
configurated (for production). During the development we can use file/console email backend.
settings.py
Implementing
We need 4 different views:
- password_reset: Form where the user submit the email address
- password_reset_done: Page displayed to the user after submitting the email form. Usually with instructions to open the email account, look in the spam folder etc. And asking for the user to click on the link he will receive.
- password_reset_confirm: The link that was emailed to the user. This view will validate the token and display a password form if the token is valid or an error message if the token is invalid (e.g. was already used or expired).
- password_reset_complete: Page displayed to the user after the password was successfully changed.
urls.py
Or you can simply include all auth views:
After including the routes in the project’s url conf, now it is a matter of creating the templates. You won’t need to mess with views.
For convenience and to avoid adding extra parameter, create a folder named registration inside your templates folder.
List of required templates:
- registration/password_reset_form.html
- registration/password_reset_subject.txt
- registration/password_reset_email.html
- registration/password_reset_done.html
- registration/password_reset_confirm.html
- registration/password_reset_complete.html
password_reset
registration/password_reset_form.html
registration/password_reset_subject.txt
(It’s just a one line file with the subject of the email that will be sent to the user).
- registration/password_reset_email.html
password_reset_done
registration/password_reset_done.html
password_reset_confirm
registration/password_reset_confirm.html
password_reset_complete
registration/password_reset_complete.html
Testing the Views
registration/password_reset_form.html
registration/password_reset_done.html
The email sent using registration/password_reset_subject.txt and registration/password_reset_email.html.
registration/password_reset_confirm.html
registration/password_reset_complete.html
Configuring a SMTP Email Service
First remove the EMAIL_BACKEND from your settings.py, since it defaults to SMTP Email Backend.
Now add the information from your email provider:
settings.py
There are many transactional email services out there. SendGrid, MailGun, Mandrill. If you want to learn more about how to configure a production-quality email service, I wrote a very detailed post about how to configure SendGrid using Django: