Photo by on Caspar Camille Rubin Unsplash In this tutorial, you’ll learn how to easily add a complete authentication system to your Django application with login, logout and password change and reset functionalities. We’ll also be using and Bootstrap 4 for styling the application UI. django-crispy-forms Prerequisites Let’s start with the prerequisites for this tutorial. In order to follow the tutorial step by step, you’ll need a few requirements, such as: Basic knowledge of Python, Working knowledge of Django ( and ), django-admin.py manage.py A recent version of Python 3 installed on your system (the latest version is ) 3.7 We will be using and which are bundled as modules in recent versions of Python so you don't actually need to install them unless you are working with old versions. pip venv If you are ready, lets go started! Creating a Virtual Environment A virtual environment allows you to isolate your current project dependencies from the rest of packages installed globally on your system or in the other virtual environments. You can either use which needs to be installed on your system or the module available as a module in recent versions of Python 3. virtualenv venv Go to your command terminal and run: $ python -m venv env Next, activate the virtual environment using: $ source env/bin/activate Note : please note that on Windows, you need to use _source env/Scripts/activate_ in order to activate your virtual environment. After activating the environment, you need to proceed by installing Django using : pip $ pip install django If the framework is successfully installed, you can now use the Django management commands to create and work with your project. Creating a Django Project Let’s now create the project using . In your terminal, run the following command: django-admin.py $ django-admin.py startproject demoproject Django has an ORM that abstracts dircet database operations and supports SQLite which is configured by default in the project so we’ll be using a SQLite database for this tutorial. If you need to use PostgreSQL, MySQL or any other database management system, you’ll have to install it first then open the of your project and add the database address and credentials inside the object. settings.py DATABASES Here is the default configuration for : sqlite DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }} Adding django-crispy-forms We’ll be using Bootstrap 4 for styling the authentication forms, so you need to install it using : pip $ pip install django-crispy-forms Next, open the file and add the application to the installed apps: settings.py INSTALLED_APPS = [ # [...] 'crispy_forms'] Next, add the following setting which sets Bootstrap 4 as the default styling framework for : django-crispy-forms CRISPY_TEMPLATE_PACK = 'bootstrap4' Creating the Application accounts Apps are the Django way of organizing a project. Think of them as modules. Let’s encapsulate the authentication logic needed in our project into an application. You obviously use any valid name you see fit. accounts Go to your terminal and navigate inside your project’s folder if you have not done so: $ cd demoproject Next, create the application using : manage.py $ python manage.py startapp accounts is another management script for Django that exists in your root project's folder. It provides a nice wrapper for the most used Django management commands. manage.py The previous command will create a Django application with a default file structure. To make this app part of your project, you need to open the file and add it to the array: settings.py INSTALLED_APPS INSTALLED_APPS = [# [...]'accounts'] That’s it, you can now create your database and run your Django development server using the following commands: $ python manage.py migrate $ python manage.py runserver You can use your browser to navigate to the address in order to see you web application up and running. localhost:8000 The Built-In Application auth The application is a built-in authentication system in Django that allows developers to add authentication to their apps without re-inventing the wheel trying to implement the base functionality from scratch. auth The Django authentication app provides the following functionalities out of the box: Login via the class view, LoginView Logout via the class view, LogoutView Password reset via the class view, PasswordResetView Password change via the class view, PasswordChangeView You only need to provide templates to implement these functions in your application. For registering users, you need to create your view and template. You need to have the app in the of the file which is the case by default. django.contrib.auth INSTALLED_APPS settings.py Next create the file in your app and add the following code: urls.py accounts from django.contrib.auth import viewsfrom django.urls import path urlpatterns = [] Login Users Using LoginView You can login users in your Django application using the class-based view. In your file add the following path: LoginView accounts/urls.py urlpatterns = [ path('login/', views.LoginView.as_view(), name='login'), You simply use the method of to return a callback object that can be assigned as a view function to the function. as_view() LoginView path() Next, you need to provide a template for your login view. Create a folder in the root of your application and add a file with the following code: templates accounts base.html <!doctype html><html lang="en"><head><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"><title>Django Authentication Example</title></head><body> <div class="container"> <div class="row justify-content-center"> <div class="col-4"> <h1 class="text-center">Django Authentication Example</h1> {% block main %} {% endblock %} </div> </div> </div></body></html> We first import Bootstrap 4 in our base HTML template. We then create a container a title and a block where Django render the other parts of our templates. <div> main Next, create a folder and the the template with the following code: templates/registration login.html {% extends 'base.html' %}{% load crispy_forms_tags %} {% block main %}<div class="card"><div class="card-body"><h4 class="card-title">Log in to your account</h4> <form method="post">{% csrf_token %}<input type="hidden" name="next" value="{{ next }}"> {{ form|crispy }} <button type="submit" class="btn btn-primary btn-block">Log in</button></form></div></div>{% endblock %} We extend the previous base template, we load and then we override the block to add our login form. crispy_forms_tags main Next, we create an HTML form with a POST method and render the form fields using ` crispy` filter applies Bootstrap styles to the individual fields. . The adds the field for CSRF protection to out login form. csrf_token We Also add a hidden form field that holds the next URL that will be used by Django to redirect the user to a next page when he’s successfully logged in. By default it redirects the URL. accounts/profile Setting the Login Redirect URL You can set the next URL or the login redirect URL via the setting. Open the file and add: LOGIN_REDIRECT_URL settings.py For testing the login view, you can create a user using the command from your terminal. manage.py createsuperuser Note : Once you are logged in, you will be redirected to the _/accounts/profile_ URL. This is a screenshot of the login form styled with Bootstrap 4: Logout Users Using LogoutView You can logout users in your application using the class-based view. In your file, add the path and link it with a callable view of : LogoutView accounts.py /logout LogoutView path('logout/', views.LogoutView.as_view(), name='logout'), Again we use the method to return a callable object from the class. as_view() LogoutView Next, you need to create a with the following code: registration/logged_out.html {% extends 'base.html' %}{% block main %} <p>You are logged out!</p><a href="{% url 'login' %}">Log in again</a> {% endblock %} This is a screenshot of the logged-out done view: Reset Passwords Using , , and PasswordResetView PasswordResetDoneView PasswordResetConfirmView PasswordResetCompleteView You can enable your users to reset their passwords using many views: , PasswordResetView , PasswordResetDoneView PasswordResetConfirmView PasswordResetCompleteView In your file, add the following paths: accounts/urls.py path('password-reset/', views.PasswordResetView.as_view(), name='password_reset'),path('password-reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'),path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), Next, you need to add a template with the following code: registration/password_reset_form.html {% extends 'base.html' %}{% load crispy_forms_tags %} {% block main %}<div class="card"><div class="card-body"><h4 class="card-title">Reset your password</h4><form method="post">{% csrf_token %}<input type="hidden" name="next" value="{{ next }}">{{ form|crispy }} <button type="submit" class="btn btn-primary btn-block">Reset</button></form></div></div></div>{% endblock %} In the same way, you need to add the , , and templates. password_reset_confirm.html password_reset_done.html password_reset_email.html password_reset_complete.html This is a screenshot of the password reset form styled with Bootstrap 4: Changing Passwords Using and PasswordChangeView PasswordChangeDoneView You can enable your users to change their passwords via the and class-based views. PasswordChangeView PasswordChangeDoneView In your file, add the following paths: accounts/urls.py path('password-change/', views.PasswordChangeView.as_view(), name='password_change'),path('password-change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'), Next create a template and add the following code: registration/password_change_form.html {% extends 'base.html' %}{% load crispy_forms_tags %} {% block main %}<div class="card"><div class="card-body"><h4 class="card-title"> Change your password</h4> <form method="post">{% csrf_token %}{{ form|crispy }} <button type="submit" class="btn btn-success">Change password </button></form></div></div>{% endblock %} You also need to add template. password_change_done.html This is a screenshot of the password change form: Registering Users For registering users, the Django built-in auth application doesn’t provide a ready view function or class-based view so you need to provide your own your own custom implementation. Importing the URLs in your Projects’ urls.py You have added the various urls for implementing authentication in your web application in the accounts application but they can not be used until you add them to the project’s level file . urls.py First, this is the complete source of the file: accounts/urls.py from django.contrib.auth import viewsfrom django.urls import path urlpatterns = [ path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('password-change/', views.PasswordChangeView.as_view(), name='password_change'), path('password-change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password-reset/', views.PasswordResetView.as_view(), name='password_reset'), path('password-reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),] Next, open the that exists in the root of your project and use the function to import the accounts urls: urls.py include() from django.urls import path, include urlpatterns = [ path('accounts/', include('accounts.urls'))] Now, go ahead and start your development server. You can use your authentication URLs under the path: /accounts for login users, http://127.0.0.1:8000/accounts/login/ for logout users, http://127.0.0.1:8000/accounts/logout/ for changing passwords, http://127.0.0.1:8000/accounts/password-change/ for resetting passwords. http://127.0.0.1:8000/accounts/password-reset/ Conclusion Throughout this tutorial we’ve seen how we can easily add the login, logout and password reset and change features in our Django apps using the application without re-inventing the wheel. auth We’ve also used Bootstrap 4 and to style the various forms for login, password change and reset. django-crispy-forms