Logout returns method not allowed
Likely cause: The browser followed a GET logout link.
Check and correct: Use a POST form with csrf_token for LogoutView.
PROJECT 5 · LESSON 9 OF 16
Use Django authentication and session cookies instead of inventing password handling.
Continue from lesson 8: Finish CRUD with edit, completion and deletion. Keep existing files; create or replace the complete files listed below.
Extract the ZIP and open the folder containing manage.py. Create a Python virtual environment, install requirements.txt and run migrate. Read README.md for checkpoint-specific commands and LESSON.md for offline explanations. Checkpoints contain no database records or private credentials.
Authentication establishes who is using the application. Instead of inventing password storage, use Django’s maintained user, password-hashing, login and session components, then add ownership rules in the next lesson.
Django already installed auth and session tables during migrate. We use its default username-based User for this course. Decide on a custom user model before your first migrations if a future project requires email-only identity.
Authentication establishes identity; the next lesson applies ownership to the task records. This checkpoint’s task routes are still shared, so keep it local.
Registration creates an account. Authentication verifies credentials and establishes identity. Authorization decides whether that identity may perform an action on a particular resource. Successful login alone does not make all task IDs safe to expose. Keep these responsibilities separate while testing.
UserCreationForm checks matching passwords and configured password validators, then uses Django’s password-setting path. The database stores a password hash, not a recoverable plain password. Never assign a raw password directly to user.password or log submitted credentials for debugging.
After login, the browser holds a session cookie. With the default database session backend, the session data lives in the database and the cookie identifies the session. SessionMiddleware and AuthenticationMiddleware reconstruct request.user on later requests. The browser does not need to send the password on every page load.
Cookies belong to a browser context. A private window starts with a separate cookie store and therefore appears logged out. That makes it useful for testing two users. Login ordinarily rotates the session key to reduce fixation risk while retaining session data; logout flushes the session. That distinction matters for the cart later.
LoginView handles credential validation and renders the configured registration/login.html template. LogoutView uses POST in this Django version; submit a CSRF-protected form instead of making logout a GET link. LOGIN_URL and LOGIN_REDIRECT_URL connect protected pages to the correct destinations.
Our course uses Django’s default user model. Decide whether you need a custom user model before the first migrations in a new real project; switching later is substantial work. For this course, usernames are the login identifier. We are not claiming email verification, password-reset delivery or social login exists.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
A visitor submits the signup form.
UserCreationForm validates the username and passwords, then creates a normal user.
The visitor submits credentials to LoginView.
Django checks the password hash and establishes a session.
Future requests receive an authenticated request.user; POST logout ends that session.
The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.
Create normal customer accounts using Django’s validated form.
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.shortcuts import render, redirect
def signup(request):
form = UserCreationForm(request.POST if request.method == "POST" else None)
if request.method == "POST" and form.is_valid():
form.save()
messages.success(request, "Account created. Sign in to continue.")
return redirect("login")
return render(request, "registration/signup.html", {"form": form})
Mount built-in login/logout views and the custom registration page.
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import include, path
from shop.accounts import signup
urlpatterns = [
path("admin/", admin.site.urls),
path("accounts/signup/", signup, name="signup"),
path("accounts/login/", auth_views.LoginView.as_view(), name="login"),
path("accounts/logout/", auth_views.LogoutView.as_view(), name="logout"),
path("tasks/", include("tasks.urls")),
path("", include("shop.urls")),
]
Provide the shared HTML document, navigation and content slots.
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}EduShop{% endblock %}</title>
<link rel="stylesheet" href="{% static 'shop/site.css' %}">
</head>
<body>
<nav aria-label="Main navigation">
<a href="{% url 'shop:home' %}">Home</a>
<a href="{% url 'shop:about' %}">About</a>
<a href="{% url 'shop:contact' %}">Contact</a>
<a href="{% url 'shop:products' %}">Products</a>
<a href="{% url 'tasks:list' %}">Tasks</a>
{% if user.is_authenticated %}
<span>Hello, {{ user.username }}</span>
<form method="post" action="{% url 'logout' %}">{% csrf_token %}<button>Sign out</button></form>
{% else %}<a href="{% url 'login' %}">Sign in</a><a href="{% url 'signup' %}">Register</a>{% endif %}
</nav>
{% for message in messages %}<p role="status">{{ message }}</p>{% endfor %}
<main>{% block content %}{% endblock %}</main>
<footer>EduShop · Built while learning Django</footer>
</body>
</html>
Render the built-in authentication form and optional return path.
{% extends "base.html" %}
{% block content %}<h1>Sign in</h1><form method="post">{% csrf_token %}{{ form.as_p }}{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}<button>Sign in</button></form><a href="{% url 'signup' %}">Create an account</a>{% endblock %}
Display registration fields and password feedback.
{% extends "base.html" %}
{% block content %}<h1>Create an account</h1><form method="post">{% csrf_token %}{{ form.as_p }}<button>Register</button></form>{% endblock %}
Try opening /admin/ with your newly registered customer.
The account does not gain staff access.
UserCreationForm creates a normal user. Staff status and model permissions are separate from having valid credentials.
Do not put a password in localStorage or a plain model field. Use Django’s authentication APIs.
Likely cause: The browser followed a GET logout link.
Check and correct: Use a POST form with csrf_token for LogoutView.
Likely cause: The redirect settings or named task route are wrong.
Check and correct: Check LOGIN_REDIRECT_URL and the route namespace; preserve a valid next destination on protected-page login.
Explain the difference between the browser session cookie and the stored password hash.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
No. It identifies server-side session state. Protecting it still matters because possession can let someone act as the signed-in visitor.
No. It establishes accounts. The next lesson must filter reads and writes by the authenticated owner.