Django User Authentication
Authentication is a fundamental aspect of web applications, allowing you to identify users and restrict access to certain parts of your site. Django provides a robust authentication system out of the box, making it easy to handle user accounts, permissions, groups, and more.
Introduction to Django Authentication
Django's authentication system handles user accounts, groups, permissions, and cookie-based user sessions. It's designed to be secure and flexible, allowing you to:
- Create new users and authenticate them
- Assign permissions to users and groups
- Manage user sessions
- Handle password hashing and validation
The system includes built-in views for common operations like login, logout, and password management, along with forms and templates for these actions.
Setting Up Authentication
Django's authentication system is included by default when you create a new project. Let's look at what you need to ensure it's properly configured:
1. Verify your settings.py
Check that the authentication middleware and apps are included in your settings.py
file:
INSTALLED_APPS = [
# ...
'django.contrib.auth',
'django.contrib.contenttypes',
# ...
]
MIDDLEWARE = [
# ...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# ...
]
2. Create a Users App (Optional)
While not required, it's common practice to create a dedicated app for user-related functionality:
python manage.py startapp users
Then add it to your INSTALLED_APPS
:
INSTALLED_APPS = [
# ...
'users',
]
User Registration
Django doesn't provide built-in views for user registration, but it's easy to create one using Django's UserCreationForm
.
Step 1: Create the Registration Form
In your users/forms.py
:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class CustomUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
Step 2: Create the Registration View
In your users/views.py
:
from django.shortcuts import render, redirect
from django.contrib.auth import login
from django.contrib import messages
from .forms import CustomUserCreationForm
def register(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
messages.success(request, f"Account created for {user.username}!")
return redirect('home') # Redirect to your home page
else:
form = CustomUserCreationForm()
return render(request, "users/register.html", {"form": form})