Django 3 Authentication with a MySQL Database— Login, Logout and Password Change/Reset
In this tutorial, you'll learn how to easily add a complete authentication system to your django 3 application with login, logout and password change and reset functionalities.
We'll be using django 3 with a MySQL database.
We'll also be using django-crispy-forms
and Bootstrap 4 for styling the application UI.
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 (
django-admin.py
andmanage.py
), - A recent version of Python 3 installed on your system (the latest version is 3.7),
- MySQL database installed on your system.
We will be using pip
and venv
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.
If you are ready, lets go started!
Creating a Virtual Environment for Your Django 3 Project
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 virtualenv
which needs to be installed on your system or the venv
module available as a module in recent versions of Python 3.
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.
We'll also need to install mysql-client using:
$ pip install mysqlclient
Creating a MySQL Database for Storing Authentication Info
We'll be using a MySQL database. In your terminal invoke the mysql
client using the following command:
ADVERTISEMENT
$ mysql -u root -p
Enter your MySQL password and hit Enter.
Next, run the following SQL statement to create a database:
mysql> create database mydb;
Creating a Django 3 Project
Let's now create the project using django-admin.py
. In your terminal, run the following command:
$ 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 settings.py
of your project and add the database address and credentials inside the DATABASES
object.
Here is the configuration for mysql
:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',
'USER': 'root',
'PASSWORD': 'YOUR_DB_PASSWORD',
'HOST': 'localhost',
'PORT': '3306',
}
}
Make sure to replace YOUR_DB_PASSWORD
with your own MySQL password.
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 settings.py
file and add the application to the installed apps:
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 accounts
Application for User Authentication
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 accounts
application. You obviously use any valid name you see fit.
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
manage.py
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.
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 settings.py
file and add it to the INSTALLED_APPS
array:
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 localhost:8000
address in order to see you web application up and running.
The auth
Built-In Application
The auth
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.
The Django authentication app provides the following functionalities out of the box:
- Login via the
LoginView
class view, - Logout via the
LogoutView
class view, - Password reset via the
PasswordResetView
class view, - Password change via the
PasswordChangeView
class view,
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 django.contrib.auth
app in the INSTALLED_APPS
of the settings.py
file which is the case by default.
Next create the urls.py
file in your accounts
app and add the following code:
from django.contrib.auth import views
from django.urls import path
urlpatterns = [
]
Login Users Using LoginView
You can login users in your Django application using the LoginView
class-based view. In your accounts/urls.py
file add the following path:
urlpatterns = [
path('login/', views.LoginView.as_view(), name='login'),
You simply use the as_view()
method of LoginView
to return a callback object that can be assigned as a view function to the path()
function.
Next, you need to provide a template for your login view. Create a templates
folder in the root of your accounts
application and add a base.html
file with the following code: