How to create forgot password feature in Django?
How to create forgot password feature in Django?
Step 1: Install Django
The first step in creating a forgot password feature in Django is to install the framework. If you haven't already installed Django on your system, use the following command in your terminal:
pip install djangoIf you're using a virtual environment, activate the environment first before running the command above. This command will install the latest version of Django on your system.
After installing Django, you can verify if it's installed correctly by running the following command:
python -m django --versionThis command should output the version of Django that you installed on your system. If you see the version number, Django is installed correctly, and you can proceed to the next step.
Once you've installed Django, you're ready to start building your forgot password feature. In the next step, we will modify the existing User model to enable the password reset functionality.
Step 2: Modify the existing User Model
One of the important steps to create the "forgot password" feature in Django is to modify the existing User Model. By default, Django provides its own User Model class. But we need to add some fields to this class to make the "forgot password" feature work. So, we need to create a new model class that inherits from Django's User Model and add the additional fields to it.
To do this, open the models.py file of your application and add the following code:
from django.contrib.auth.models import AbstractUserclass CustomUser(AbstractUser): # add additional fields here pass
In the above code, we created a new class "CustomUser" that inherits from Django's default User Model class (AbstractUser). We have not added any fields yet, but we can do so by adding the required fields inside the class definition. Once we have created the custom User Model, we need to tell Django to use it instead of the default User Model. To do this, add the following line to your settings.py file:
AUTH_USER_MODEL = '.CustomUser'
Replace <your_app_name> with the name of your Django application. This line tells Django to use our custom user model instead of the default user model.
After making these changes, run the following command to make the database migrations:
python manage.py makemigrationspython manage.py migrate
Now, our custom user model is ready to be used in the "forgot password" feature.
Step 3: Create Password Reset View
Once you have modified the User model, it's time to create a Password Reset View. This view will handle the password reset email request and send the email to the user's email account. Here's how to create this view:
1. Open yourviews.py file and add the following code:from django.contrib.auth.views import PasswordResetViewclass MyPasswordResetView(PasswordResetView): template_name = 'my_app/password_reset.html' email_template_name = 'my_app/password_reset_email.html' subject_template_name = 'my_app/password_reset_subject.txt' success_url = reverse_lazy('password_reset_done')2. In the above code, we're extending Django's built-in PasswordResetView and adding our customizations such as specifying the template names for the password reset form, email, and subject, as well as the success URL after password reset is completed.3. Next, add the URL pattern for this view in your urls.py file:from django.urls import pathfrom .views import MyPasswordResetViewurlpatterns = [ # other URL patterns path('password_reset/', MyPasswordResetView.as_view(), name='password_reset'),]4. Now you can visit the password reset URL in your browser and enter the email address of the user whose password needs to be reset. Django will then send an email to that email address with instructions on how to reset their password.With this view in place, your users can now reset their passwords if they forget them.
Step 4: Create Template for Password Reset View
In this step, we'll create a template for the password reset view. This template will be responsible for rendering the HTML for the password reset form. We'll use Django's built-in password reset form for this.
To create the template, create a new file called password_reset_form.html inside the templates/registration directory. Add the following code to it:
{% extends 'registration/base.html' %}{% block content %} {% endblock %}In this template, we're extending the base.html template and defining a content block where we're creating a form with an email input field and a submit button. We've also included the {% csrf_token %} template tag for security purposes.
After creating the template, we need to update the PASSWORD_RESET_TEMPLATE setting in settings.py to point to this new template. Add the following line to settings.py:
PASSWORD_RESET_TEMPLATE = 'registration/password_reset_form.html'With this, the password reset view will use our new template when rendering the password reset form.
Learn more about sending emails in Django.
Step 5: Create Password Reset Confirm View
After the user has requested a password reset, they will receive an email containing a link to confirm the reset. In this step, we will create a view that handles this confirmation process.To create the PasswordResetConfirmView, start by importing the built-in PasswordResetConfirmView from Django and the custom PasswordResetConfirmForm we created in the previous step.from django.contrib.auth.views import PasswordResetConfirmViewfrom path_to_your_forms_file import PasswordResetConfirmFormNext, define the view class and set the template for it to use.class CustomPasswordResetConfirmView(PasswordResetConfirmView): template_name = 'your_template_name.html' form_class = PasswordResetConfirmFormEnsure that you replace `'your_template_name.html'` with the actual name of the template you created in Step 4.Finally, update the URLconf with the new view.from django.urls import pathfrom .views import CustomPasswordResetConfirmViewurlpatterns = [ #... other urls path('reset///', CustomPasswordResetConfirmView.as_view(), name='password_reset_confirm'),] The `uidb64` and `token` parameters in the URL are passed to the view from the password reset email link. With this, we have completed the creation of the Password Reset Confirm View. It is now time to move on to the next step and create a template for it.Step 6: Create Template for Password Reset Confirm View
Now that we have created the password reset confirm view, let's create a template to display the success message to the user. In Django, templates are used to render HTML pages dynamically. We will create a simple template with a success message for the password reset confirm view.
Let's create a new directory called templates inside the main app directory. Inside the templates directory, create another directory called registration. This is the default directory Django searches for templates for the built-in user authentication views.
<app_name>/templates/registration/password_reset_complete.htmlInside the password_reset_complete.html file, add the following code:
{% extends 'base.html' %}{% block content %} <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header"></div> <div class="card-body"> <h4>Password reset complete!</h4> <p>Your password has been successfully reset.</p> </div> </div> </div> </div> </div>{% endblock %}This template extends from the 'base.html' file which should already exist in your templates directory. It displays a success message to the user after their password has been successfully reset.
Now that we have our template, we need to tell Django to use it. In our views.py file, we need to specify the template name for the password reset confirm view:
from django.contrib.auth.views import PasswordResetCompleteViewclass PasswordResetCompleteView(PasswordResetCompleteView): template_name = 'registration/password_reset_complete.html'With this added, our password reset confirm view will now render the template we just created.
Next, we will configure email settings to allow our users to receive password reset emails.
Step 7: Configure Email Settings
The forgot password feature requires an email to send a reset link to the user. In this step, we will configure the email settings for Django in our project's settings.py file.
To configure email settings, add the following code to the settings.py file:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'EMAIL_HOST = 'smtp.gmail.com'EMAIL_PORT = 587EMAIL_USE_TLS = TrueEMAIL_HOST_USER = 'your-email@gmail.com'EMAIL_HOST_PASSWORD = 'your-email-password'Make sure to replace 'your-email@gmail.com' and 'your-email-password' with your actual email address and password. In the code above, we are using the SMTP backend which allows Django to send emails using a Simple Mail Transfer Protocol (SMTP) server. We are also specifying the email host (Gmail SMTP server), email port (587), and enabling TLS (Transport Layer Security) encryption.
There are other email backends available for Django as well, including console and file-based email backends, which are useful when developing locally. You can check out the Django documentation for more information on available email backends.
Now that we've configured the email settings, we can move on to testing our forgot password feature.
Step 8: Test Your Forgot Password Feature
Once you have implemented the forgot password feature in Django, it's time to test it thoroughly to make sure it works as expected. To test the feature, follow the steps below:1. Open a browser and navigate to the login page of your application.2. Click on the "Forgot password?" link to access the password reset page.3. Enter a valid email address associated with your account and click on the "Reset my password" button.4. Check your email for a password reset link. Click on the link and reset your password.5. Login to your account using the new password to verify that the password has been reset successfully.Testing your forgot password feature is an essential step to ensure that your application is secure and user-friendly. Make sure to test it thoroughly before deploying your application to users.python manage.py testIt's also a good idea to run automated tests using Django's testing framework. This will help you catch any unexpected errors or issues before deploying your application to production.Congratulations! You have successfully created and tested the forgot password feature in Django.Django official documentation on resetting a password
Tutorial on how to create a password reset view in Django by Simple Is Better Than Complex
Django Allauth documentation on email authentication
Django source code for the password reset form
Twilio blog post on how to add SMS password reset functionality in Django