A Django FotoBlog in VS Code — Self-Service Password Reset

How To Create A FotoBlog in VS Code — Part III — DjangoSeries Episode # 17

J3
Jungletronics
9 min readMar 26, 2023

--

Django provides a built-in password reset functionality that allows users to reset their passwords if they forget them.

The password reset functionality works as follows:

1. User clicks on the forgot password link on the login page;

2. Django generates a unique token and sends an email to the user
with a link to the password reset page that includes the token;

3. User clicks on the link in the email, which takes them to the
password reset page;

4. The user enters their new password and submits the form;

5 . Django validates the token and updates the user’s password.

This is our journey for this episode. Welcome!

00 #Step — Complete this previous episode or hit the download zip button Episode.02 and follows the instruction on my repo read me👌️

01 #Step —Use the built-in authentication views: open fotoblog/urls.py and type:

...
from django.urls import path, include

urlpatterns = [
...
path('accounts/', include('django.contrib.auth.urls')),
]

The django.contrib.auth.urls module in Django provides a set of pre-built URL patterns that are commonly used in authentication workflows, such as login, logout, password reset, and so on.

This module contains a number of built-in views and URL patterns that can be used to handle user authentication in Django.

These views include:

  • LoginView: This view displays a login form and handles user authentication.
  • LogoutView: This view logs out the authenticated user and redirects to a specified URL.
  • PasswordResetView: This view displays a form that allows the user to reset their password if they have forgotten it.
  • PasswordResetDoneView: This view displays a message after the user has requested a password reset.
  • PasswordResetConfirmView: This view allows the user to confirm their new password after they have requested a password reset.
  • PasswordResetCompleteView: This view displays a message after the user has successfully reset their password.

By including the URL patterns from django.contrib.auth.urls in your project's URLconf, you can easily wire up these authentication views to the appropriate URLs in your application. For example, please keep reading…

02 #Step —Now open fotoblog/settings.py

TEMPLATES = [
{
...
'DIRS': [BASE_DIR / 'templates'],
...

The DIRS setting in Django is a list of directories where Django looks for templates to render. In the specific case we mentioned, DIRS: [BASE_DIR / 'templates'], it tells Django to look for templates in a directory called "templates" that is located in the project's base directory.

Here’s a breakdown of what each part of this setting means:

  • BASE_DIR is a constant that is defined in Django's default settings file. It refers to the base directory of the project, which is the directory that contains the manage.py file.
  • / 'templates' is simply a string that specifies the name of the subdirectory where the templates are located.
  • Putting BASE_DIR / 'templates' together means that Django will look for templates in the "templates" directory that is located in the project's base directory.

By default, Django looks for templates in a directory called templates that is located within each app in your project. However, by adding BASE_DIR / 'templates' to the DIRS setting, you can specify a separate directory for your project-wide templates that is not associated with any specific app.

Overall, this setting allows we to centralize your project’s templates in a single directory, making it easier to manage and organize your code.

03 #Step — Continuing on fotoblog/settings.py and at the end type:

LOGIN_REDIRECT_URL = 'login'
LOGOUT_REDIRECT_URL = 'login'

EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = BASE_DIR / 'emails'

The settings we listed (LOGIN_REDIRECT_URL, LOGOUT_REDIRECT_URL, EMAIL_BACKEND, and EMAIL_FILE_PATH) are all configuration settings in a Django application. Here's what each of these settings does:

  • LOGIN_REDIRECT_URL: This setting specifies the URL to redirect to after a user logs in. In this case, the value is 'login', which means that after a successful login, the user will be redirected to the 'login' URL (presumably the login page).
  • LOGOUT_REDIRECT_URL: This setting specifies the URL to redirect to after a user logs out. In this case, the value is also 'login', which means that after a successful logout, the user will be redirected to the 'login' URL.
  • EMAIL_BACKEND: This setting specifies the backend used for sending emails in the application;
  • The value 'django.core.mail.backends.filebased.EmailBackend' indicates that Django should save emails to a file instead of sending them through an SMTP server;
  • EMAIL_FILE_PATH: This setting specifies the directory where emails should be saved when EMAIL_BACKEND is set to 'django.core.mail.backends.filebased.EmailBackend';
  • The value BASE_DIR / 'emails' specifies a sub-directory called 'emails' within the base directory of the project.

These settings are typically defined in a Django settings module (often named settings.py) in the root directory of the project. By setting these values, we can configure how user authentication and email functionality work in your Django application.

04 #Step — Create on the project root a directory called templates/registration and save inside 5 html files (or download it now from here, if you prefer 🥰️.

1– templates/registration/login.html:

<h1>Log in</h1>

{% if request.user.is_authenticated %}
<p>You are Logged in!</p>

<a href="{% url 'logout' %}">Log out</a>

{% else %}

<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log in</button>
</form>

{% endif %}

2- templates/registration/password_reset_form.html:

<h1>Forgot your password?</h1>
<p>Enter your email address below</p>

<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>

3- : templates/password-reset-confirm.htlm

{% if validlink %}
<h1>Set new password</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
{% else %}
<p>The Validation link is not valid!</p>
{% endif %}

4- templates/registration/password_reset_done.html:

<h1>Thank you</h1>
<p>You should receive the email shortly</p>

5- templates/registration/password_reset_complete.html:

<h1>Password reset complete!</h1>
<p>You can now log in here: <a href=" {% url 'login' %} ">Log in</a></p>

To understand this, please refers the graphic here or read this post.

Django’s Authentication views help manage password resets for users without superuser status. See better here 👈 or here; Forget pw? -> password_reset; Set now! -> password_reset_confirm; You should receive an email briefly… -> password_reset_done; Now login! -> password_reset_complete

The templates we listed are all part of Django’s built-in authentication system. Here’s what each of these templates does:

  • templates/registration/login.html: This template is used to render the login form. It typically includes fields for the user to enter their username and password, as well as any necessary styling or messaging.
  • templates/registration/password_reset_form.html: This template is used to render the form where users can request a password reset. It typically includes fields for the user to enter their email address (or username, depending on how your authentication system is set up), as well as any necessary styling or messaging.
  • templates/registration/password_reset_confirm.html: This template is used to render the page where users can enter a new password after clicking the link in the password reset email they receive. It typically includes fields for the user to enter and confirm their new password, as well as any necessary styling or messaging.
  • templates/registration/password_reset_done.html: This template is used to render the page that users see after submitting a password reset request. It typically includes a message informing the user that an email has been sent with instructions on how to reset their password, as well as any necessary styling or messaging.
  • templates/registration/password_reset_complete.html: This template is used to render the page that users see after successfully resetting their password. It typically includes a message informing the user that their password has been reset, as well as any necessary styling or messaging.

By default, Django uses these templates as part of its built-in authentication system, but you can customize them or replace them with your own templates as needed. The templates are typically stored in a templates directory within your Django project, with sub-directories corresponding to each app that provides templates. As above, the authentication templates would typically be stored in templates/registration/ within your project.

05 #Step — Run python manage.py runserverand route to localhost:8000/accounts/

Django is telling you that you must type of one of these urls…Fine. Just good! In the next tutorial we will fix that…

06 #Step — To login we need a superuser. On terminal, type this and follows the instructions (you must register an valid email for the sake of this episode):

python manage.py createsuperuser

In Django, a superuser is a user with special privileges and permissions to access and manage the admin site. When you create a Django project, by default, it comes with an administrative interface that allows you to manage the application’s data, users, and settings.

A superuser account is created during the installation of Django, and it has access to all the functionalities of the Django admin site. As a superuser, you can add, edit, and delete any object from the database, including users and their permissions. You can also manage Django settings, such as installed apps, middleware, and database configurations.

Creating a superuser account is useful when developing and deploying a Django application, as it allows you to manage the application’s data and settings easily. You can also assign specific permissions to other users, so they can manage specific parts of the admin site without having full access to everything.

Overall, creating a superuser account is a necessary step when building a Django project to ensure that the application is secure and well-managed.

07#Step — Now route to localhost:8000/login and enter with your credential. Here is my example:

My user & pass…hit Log in… http://127.0.0.1:8000/accounts/login/
Here I logged! http://127.0.0.1:8000/accounts/login/
http://127.0.0.1:8000/accounts/password_reset/, when I hit Send…
http://127.0.0.1:8000/accounts/password_reset/done/
As you can see, everything works fine! An email was received. Now click the link…
This is the password confirm! Hit Send…
You are back to system!

If you want to set your SMTP please refers to this post to see how.

Let’s Recap!

Django provides built-in functionality for password reset via email. This feature allows users to reset their password if they forget it or want to change it for security reasons. Here’s how the password reset process typically works:

  1. The user clicks the “forgot password” link on the login page, which takes them to a form where they can enter their email address (or username, depending on how your authentication system is set up).
  2. When the user submits the form, Django generates a one-time use token and sends an email to the user with a link to a password reset form that includes the token.
  3. The user clicks the link in the email, which takes them to the password reset form. The form includes the token in the URL to ensure that it’s valid and has not been tampered with.
  4. The user enters a new password and submits the form.
  5. Django verifies that the token is still valid and has not already been used. If the token is valid, Django updates the user’s password and redirects them to a success page.

To enable this functionality in Django, you’ll need to do a few things:

  1. Set the EMAIL_BACKEND setting to a backend that can send emails, such as django.core.mail.backends.smtp.EmailBackend.
  2. Set up your email server settings, such as EMAIL_HOST, EMAIL_PORT, EMAIL_USE_TLS, EMAIL_HOST_USER, and EMAIL_HOST_PASSWORD, depending on your email provider.
  3. Include the django.contrib.auth.urls URLconf in your project's URLconf. This will give you the built-in authentication views, including the password reset views.
  4. Create the templates for the password reset views, including password_reset_form.html, password_reset_email.html, password_reset_subject.txt, password_reset_confirm.html, password_reset_done.html, and password_reset_complete.html, or customize the default templates as needed.

Once you’ve done these steps, you should be able to use the built-in password reset functionality in your Django application.

In the next episode we will make our first View, finally.

See you there!

bye for now!

References & Credits

Create a Web Application With Django by openclassrooms.com

DBeaver Community 23.0.0 by dbeaver.io

A Django Blog In VS Code — Quick Start! by jungletronics

Tagging:

Note: run in one line in the terminal.

git tag -a Episode.03 -m "FotoBlog - v1.0:  from http://jungletronics.com" 
-m "Third Episode Tutorial - DjangoSeries - Step-by-step list:"
-m "1-Explainning how password reset functionality works;"
-m "2-Modifying fotoblog/urls.py file;"
-m "3-Modifying fotoblog/settings.py file"
-m "4-Creating 5 htmls file at templates/registration;"
-m "3-Routing at localhost:800/accounts/ dirs."


git push origin Episode.03

Note: on GitHub Repo click tag. I am using Python 3.7.6 Django 3.2.18.

Nave-Gate-Tuts-Parts: I . II . III . IV . V . VI . VII . VIII . IX . X

--

--

J3
Jungletronics

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Ruby, Rails, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!