Almost every web application needs authentication:
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:
By the end, you will have a complete authentication system ready for real-world applications.
By the end of this tutorial, you will understand:
You should already know:
Django provides built-in tools for authentication:
The default user model is:
from django.contrib.auth.models import User
UserCreationFormDjango provides a ready-to-use form for registration.
forms.pyfrom django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'password1', 'password2']views.pyfrom 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})signup.html<h1>Sign Up</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>Django provides built-in authentication functions.
views.pyfrom 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')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>Logging out is very simple.
from django.contrib.auth import logout
from django.shortcuts import redirect
def logout_view(request):
logout(request)
return redirect('login')urls.pyfrom 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'),
]Some pages should only be accessible to logged-in users.
login_requiredfrom django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
return render(request, 'dashboard.html')If a user is not logged in, Django redirects to:
LOGIN_URL = '/login/'Set this in settings.py:
LOGIN_URL = 'login'Django provides useful variables in templates.
{% if user.is_authenticated %}
<p>Welcome {{ user.username }}</p>
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
{% endif %}<p>Username: {{ user.username }}</p>
<p>Email: {{ user.email }}</p>Instead of writing your own login view, you can use Django’s built-in view.
urls.pyfrom django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
]path('logout/', auth_views.LogoutView.as_view(), name='logout')Set in settings.py:
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'login'Django provides built-in views for password change.
urls.pyfrom 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'),
]Django supports email-based password reset.
urls.pyurlpatterns += [
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.
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class DashboardView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard.html'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.
Always include:
{% csrf_token %}login_requiredSensitive pages should be protected.
Make sure LOGIN_URL is set correctly.
Always check:
if user is not None:login_required@login_required
def dashboard(request):
return render(request, 'dashboard.html')<h1>Dashboard</h1>
<p>Welcome {{ user.username }}</p>In this tutorial, you learned:
UserCreationFormauthenticate() and login()logout()login_requiredAuthentication is a core feature in almost every Django project.
A. signin()
B. login()
C. auth()
D. enter()
A. secure_view
B. auth_required
C. login_required
D. protect_view
A. LoginForm
B. UserForm
C. UserCreationForm
D. RegisterForm
A. exit()
B. logout()
C. leave()
D. close()
A. user.logged
B. user.is_authenticated
C. user.status
D. user.active
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.