Introduction
Almost every web application needs authentication:
- users must register
- users must log in
- users must log out
- some pages must be protected
- users must manage passwords
Django provides a powerful built-in authentication system that handles all of this for you.
In this tutorial, you will learn how to use Django’s authentication system to build:
- user registration (signup)
- login and logout
- protected pages
- password management
By the end, you will have a complete authentication system ready for real-world applications.
What You Will Learn
By the end of this tutorial, you will understand:
- Django’s authentication system basics
- how to create users
- how to log users in and out
- how to protect views (login required)
- how to use authentication forms
- how to display user information in templates
- best practices for authentication
Prerequisites
You should already know:
- Django models
- views and templates
- forms
- URLs and routing
1. Django Authentication System Overview
Django provides built-in tools for authentication:
- User model → stores users
- Authentication functions → login/logout
- Forms → login/signup forms
- Permissions system → control access
The default user model is:
from django.contrib.auth.models import User
2. Creating Users (Signup)
Method 1: Using UserCreationForm
Django provides a ready-to-use form for registration.
forms.py
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'password1', 'password2']View for Signup
views.py
from django.shortcuts import render, redirect
from .forms import SignUpForm
def signup_view(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = SignUpForm()
return render(request, 'accounts/signup.html', {'form': form})Template: signup.html
<h1>Sign Up</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>3. User Login
Django provides built-in authentication functions.
View for Login
views.py
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
def login_view(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('home')
else:
return render(request, 'accounts/login.html', {'error': 'Invalid credentials'})
return render(request, 'accounts/login.html')Template: login.html
<h1>Login</h1>
{% if error %}
<p style="color:red;">{{ error }}</p>
{% endif %}
<form method="post">
{% csrf_token %}
<input type="text" name="username" placeholder="Username"><br>
<input type="password" name="password" placeholder="Password"><br>
<button type="submit">Login</button>
</form>4. User Logout
Logging out is very simple.
View
from django.contrib.auth import logout
from django.shortcuts import redirect
def logout_view(request):
logout(request)
return redirect('login')5. URLs Configuration
urls.py
from django.urls import path
from .views import signup_view, login_view, logout_view
urlpatterns = [
path('signup/', signup_view, name='signup'),
path('login/', login_view, name='login'),
path('logout/', logout_view, name='logout'),
]6. Protecting Views (Login Required)
Some pages should only be accessible to logged-in users.
Using login_required
from django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
return render(request, 'dashboard.html')Redirect Behavior
If a user is not logged in, Django redirects to:
LOGIN_URL = '/login/'Set this in settings.py:
LOGIN_URL = 'login'7. Using Authentication in Templates
Django provides useful variables in templates.
Check if user is logged in
{% if user.is_authenticated %}
<p>Welcome {{ user.username }}</p>
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
{% endif %}8. Display Current User Info
<p>Username: {{ user.username }}</p>
<p>Email: {{ user.email }}</p>9. Using Built-in LoginView (Shortcut)
Instead of writing your own login view, you can use Django’s built-in view.
urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
]10. Using Built-in LogoutView
path('logout/', auth_views.LogoutView.as_view(), name='logout')11. Redirect After Login
Set in settings.py:
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'login'12. Password Change
Django provides built-in views for password change.
urls.py
from django.contrib.auth import views as auth_views
urlpatterns += [
path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'),
path('password_change_done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'),
]13. Password Reset (Forgot Password)
Django supports email-based password reset.
urls.py
urlpatterns += [
path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),
path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'),
]This requires email configuration.
14. Using Authentication with Class-Based Views
Protect CBVs
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class DashboardView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard.html'15. Customizing the User Model (Important Note)
Django allows you to create a custom user model.
For beginners, use the default User.
For advanced projects, consider:
AUTH_USER_MODEL = 'yourapp.CustomUser'But only if needed.
16. Common Mistakes
Forgetting CSRF token
Always include:
{% csrf_token %}Not using login_required
Sensitive pages should be protected.
Incorrect login URL
Make sure LOGIN_URL is set correctly.
Not handling invalid login
Always check:
if user is not None:17. Best Practices
- use Django’s built-in authentication system
- protect private views with
login_required - use built-in views when possible
- keep authentication simple at first
- later add features like email verification
18. Mini Project: Authentication System
Features
- signup page
- login page
- logout button
- dashboard page (protected)
Dashboard Example
@login_required
def dashboard(request):
return render(request, 'dashboard.html')Template
<h1>Dashboard</h1>
<p>Welcome {{ user.username }}</p>19. Summary
In this tutorial, you learned:
- Django provides a built-in authentication system
- users can register using
UserCreationForm - users can log in using
authenticate()andlogin() - users can log out using
logout() - views can be protected with
login_required - templates can access user information
- built-in views simplify authentication tasks
Authentication is a core feature in almost every Django project.
20. Mini Quiz
1. Which function logs a user in?
A. signin()
B. login()
C. auth()
D. enter()
2. Which decorator protects views?
A. secure_view
B. auth_required
C. login_required
D. protect_view
3. Which form is used for registration?
A. LoginForm
B. UserForm
C. UserCreationForm
D. RegisterForm
4. Which function logs a user out?
A. exit()
B. logout()
C. leave()
D. close()
5. How do you check if a user is logged in?
A. user.logged
B. user.is_authenticated
C. user.status
D. user.active
21. What Comes Next?
Next tutorial:
Tutorial: User Registration System (Advanced)
You will learn how to build a more advanced signup system with custom forms, validation, and user profiles.
💬 Comments
No comments yet. Be the first to comment!
Login to comment.