Authentication is one of the most important parts of a real-world web application. It allows users to create accounts, log in, log out, and access pages that require authentication.
In this lesson, we will build a practical Django Authentication Project using Django's built-in authentication system. We will cover registration, login, logout, protected pages, sessions, password handling, and basic user management.
login_required.
Authentication is the process of verifying the identity of a user.
For example, when a user enters a username and password, the application checks whether those credentials belong to a valid account.
Username
+
Password
↓
Authentication
↓
User Account
Authentication and authorization are related but different concepts.
For example, a user may successfully log in but may not have permission to delete another user's post.
Django includes a built-in authentication framework.
The authentication system provides:
Django provides a built-in User model through
django.contrib.auth.models.
from django.contrib.auth.models import User
The User model provides fields and functionality for managing user accounts.
Django projects normally include the authentication application in
INSTALLED_APPS.
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
These built-in applications provide authentication and session support.
Run migrations to create the database tables required by Django's built-in authentication system.
python manage.py migrate
This creates tables for users, permissions, groups, sessions, and other built-in Django components.
Create a Django administrator account using:
python manage.py createsuperuser
Django will ask for information such as username, email, and password.
A user can also be created from Python code.
from django.contrib.auth.models import User
user = User.objects.create_user(
username="rahul",
email="rahul@example.com",
password="StrongPassword123"
)
Use create_user() rather than assigning a raw password directly
to the password field.
Django does not normally store user passwords as plain text. Django's authentication system handles password hashing and verification.
For example:
user.set_password(
"NewPassword123"
)
user.save()
This should be used when setting or changing a user's password.
A simple registration form can use Django's User model.
from django import forms
from django.contrib.auth.models import User
class RegistrationForm(forms.ModelForm):
password = forms.CharField(
widget=forms.PasswordInput
)
class Meta:
model = User
fields = [
"username",
"email",
"password"
]
For production applications, password validation and confirmation fields should also be handled carefully.
The registration view receives user information and creates an account.
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib import messages
def register(request):
if request.method == "POST":
username = request.POST.get(
"username"
)
email = request.POST.get(
"email"
)
password = request.POST.get(
"password"
)
User.objects.create_user(
username=username,
email=email,
password=password
)
messages.success(
request,
"Account created successfully."
)
return redirect(
"login"
)
return render(
request,
"accounts/register.html"
)
<h2>
Create Account
</h2>
<form method="post">
{% csrf_token %}
<input
type="text"
name="username"
placeholder="Username"
required
>
<input
type="email"
name="email"
placeholder="Email"
required
>
<input
type="password"
name="password"
placeholder="Password"
required
>
<button type="submit">
Register
</button>
</form>
Before creating a user, you can check whether the username already exists.
if User.objects.filter(
username=username
).exists():
messages.error(
request,
"Username already exists."
)
This prevents duplicate usernames from causing registration problems.
Django provides the authenticate() function for checking user
credentials.
from django.contrib.auth import authenticate
user = authenticate(
username=username,
password=password
)
If the credentials are valid, Django returns the authenticated user.
Otherwise, it returns None.
After successful authentication, use Django's login()
function to create the authenticated session.
from django.contrib.auth import login
login(
request,
user
)
The user can then access authenticated pages.
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib import messages
def user_login(request):
if request.method == "POST":
username = request.POST.get(
"username"
)
password = request.POST.get(
"password"
)
user = authenticate(
request,
username=username,
password=password
)
if user is not None:
login(
request,
user
)
return redirect(
"dashboard"
)
messages.error(
request,
"Invalid username or password."
)
return render(
request,
"accounts/login.html"
)
<h2>
Login
</h2>
<form method="post">
{% csrf_token %}
<input
type="text"
name="username"
placeholder="Username"
required
>
<input
type="password"
name="password"
placeholder="Password"
required
>
<button type="submit">
Login
</button>
</form>
Django provides the logout() function.
from django.contrib.auth import logout
def user_logout(request):
logout(request)
return redirect(
"login"
)
The user's authentication session is cleared.
The login_required decorator protects a view from unauthenticated
users.
from django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
return render(
request,
"accounts/dashboard.html"
)
If the user is not logged in, Django redirects the request to the configured login URL.
The login URL can be configured in settings.py.
LOGIN_URL = "/login/"
This tells Django where users should be redirected when authentication is required.
Django provides the current user through request.user.
def dashboard(request):
print(
request.user
)
return render(
request,
"accounts/dashboard.html"
)
In an authenticated view, request.user represents the logged-in
user.
Use is_authenticated to check whether the current user is
authenticated.
if request.user.is_authenticated:
print("User is logged in")
In templates:
{% if user.is_authenticated %}
Welcome, {{ user.username }}
{% endif %}
{% if user.is_authenticated %}
<p>
Welcome {{ user.username }}
</p>
<a href="{% url 'dashboard' %}">
Dashboard
</a>
<a href="{% url 'logout' %}">
Logout
</a>
{% else %}
<a href="{% url 'login' %}">
Login
</a>
<a href="{% url 'register' %}">
Register
</a>
{% endif %}
from django.urls import path
from . import views
urlpatterns = [
path(
"register/",
views.register,
name="register"
),
path(
"login/",
views.user_login,
name="login"
),
path(
"logout/",
views.user_logout,
name="logout"
),
path(
"dashboard/",
views.dashboard,
name="dashboard"
),
]
auth_project/
│
├── manage.py
│
├── auth_project/
│ ├── settings.py
│ ├── urls.py
│ ├── asgi.py
│ └── wsgi.py
│
└── accounts/
├── migrations/
├── templates/
│ └── accounts/
│ ├── register.html
│ ├── login.html
│ └── dashboard.html
│
├── __init__.py
├── admin.py
├── apps.py
├── forms.py
├── models.py
├── urls.py
├── views.py
└── tests.py
Register
↓
Create User
↓
Login
↓
Authenticate Credentials
↓
Create Session
↓
Access Protected Page
↓
Logout
↓
Session Ends
This is the basic flow of a Django authentication system.
Django provides password validators that can be configured in
AUTH_PASSWORD_VALIDATORS.
The default project configuration can include validators for:
These validators can help enforce stronger password requirements.
{% csrf_token %} in POST forms.login() after authentication.User Registration
↓
User Account Created
↓
Login Form
↓
authenticate()
↓
login()
↓
Session Created
↓
Dashboard
↓
login_required
↓
Protected Content
↓
logout()
↓
Login Page
The Django Authentication Project combines Django's built-in authentication tools to create a complete user access system.
create_user() to create users.authenticate() to verify credentials.login() to create an authenticated session.logout() to log a user out.login_required to protect views.request.user to access the current user.is_authenticated to check login status.authenticate() checks user credentials.login() creates an authenticated session.logout() ends the user's authenticated session.login_required protects private views.request.user provides the current user.Question: Which Django function is used to verify a username and password?