Login and Logout
Goal for this part
Give Campus Press a session-based login and logout flow. You will wire Django’s built-in authentication views, add templates for them, and protect at least one page with @login_required.
After this snapshot, anonymous visitors should be redirected to login when they hit a protected URL, and the nav should reflect auth state.
What you should already know
You should be able to register a user from the previous part. A basic sense of why passwords are hashed will help the security pieces click.
You do not need to write login from scratch—Django’s LoginView and LogoutView cover the common case.
Concepts: auth views and LOGIN_REDIRECT_URL
Authentication views live in django.contrib.auth.views. You point URL patterns at them and supply templates like users/login.html. Settings such as LOGIN_REDIRECT_URL and LOGIN_URL control where users go after login and where protected views send strangers.
The @login_required decorator (or LoginRequiredMixin for class-based views) enforces access before your view body runs.
from django.contrib.auth import views as auth_views
from django.urls import path
urlpatterns = [
path(
"login/",
auth_views.LoginView.as_view(template_name="users/login.html"),
name="login",
),
path(
"logout/",
auth_views.LogoutView.as_view(template_name="users/logout.html"),
name="logout",
),
]
Walkthrough: nav and a protected page
In base.html, use {% if user.is_authenticated %} to show logout versus login/register links. The user variable is available in templates when the auth context processor is enabled (default in Django projects).
Decorate a sample view—or the profile route you will flesh out next—with @login_required and confirm the redirect goes to your login page.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@login_required
def profile(request):
return render(request, "users/profile.html")
How to run it and what you should see
Run 06-Login-Logout, register or use an existing user, log in, visit a protected page, then log out and try again. You should land on login when anonymous.
git clone https://github.com/michaeldunga1/fcc-django-blog.git
cd fcc-django-blog/06-Login-Logout
python3 -m venv .venv
source .venv/bin/activate
pip install -r ../requirements.txt
python manage.py migrate
python manage.py runserver
Common mistakes and troubleshooting
If login succeeds but you bounce oddly, check LOGIN_REDIRECT_URL. If @login_required sends you to the wrong place, set LOGIN_URL to your login route name or path.
CSRF errors on the login form usually mean the template is missing {% csrf_token %} inside the <form>.
Try this checklist
- Log in and confirm the nav switches
- Log out and confirm protected URLs redirect
- Try a wrong password and read the error
- Confirm CSRF token is present on the login form
Next: Profiles and Images
Comments
One comment per signed-in account. Comments are saved with this page’s URL.