In Part 2, you learned how to create forms and accept user input. Now it’s time to handle user authentication. In this post, you’ll add login, logout, and registration functionality using Django’s built-in auth system.
What You’ll Learn
- Enable Django’s auth system
- Create user registration (sign up) form
- Add login and logout functionality
- Secure pages to logged-in users only
Step 1: Configure URLs
Django provides built-in views for login and logout. First, update myproject/urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
path('accounts/', include('django.contrib.auth.urls')), # Login/Logout
]
Step 2: Create Registration View
Create a view in myapp/views.py
:
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login') # Redirect to login after signup
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
Step 3: Create Registration Template
Create templates/registration/register.html
:
<h2>Sign Up</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
Step 4: Add Registration URL
In myapp/urls.py
:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('create/', views.create_post, name='create_post'),
path('register/', views.register, name='register'),
]
Step 5: Create Login & Logout Templates
Create templates/registration/login.html
:
<h2>Login</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
<p>Don't have an account? <a href="{% url 'register' %}">Sign up</a></p>
Django automatically logs out users at /accounts/logout/
. You can create a basic logout confirmation template at templates/registration/logged_out.html
:
<h2>You have been logged out.</h2>
<a href="{% url 'login' %}">Log in again</a>
Step 6: Secure Views with Login Required
To restrict access to views, use the login_required
decorator:
from django.contrib.auth.decorators import login_required
@login_required
def create_post(request):
...
Step 7: Redirect After Login
In myproject/settings.py
add:
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/accounts/login/'
Conclusion
You’ve successfully added user authentication to your Django app, including login, logout, and user registration. With authentication in place, you can now build dashboards, user-specific features, and protected content.
Coming Next in Part 4: Learn how to add user profiles and permissions!