Skip to lesson content

PROJECT 5 · LESSON 9 OF 16

Add registration, login and logout

Use Django authentication and session cookies instead of inventing password handling.

  • UserCreationForm
  • LoginView
  • sessions
  • password hashing

Your workspace: edushop

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.

1. Understand the problem and the concepts

Why we need this feature

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, authentication and authorization differ

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.

How the browser stays logged in

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.

Use the built-in views deliberately

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.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. A visitor submits the signup form.

  2. UserCreationForm validates the username and passwords, then creates a normal user.

  3. The visitor submits credentials to LoginView.

  4. Django checks the password hash and establishes a session.

  5. Future requests receive an authenticated request.user; POST logout ends that session.

Test browser identity

  1. Register a normal account and log in.
  2. Open the same site in a private window. It should show a logged-out visitor.
  3. Log out in the original window using the form and refresh a page. The authenticated identity is gone.

3. Build it, one file at a time

  1. Add the registration view, auth URLs and templates. Update the base template to show the user and a POST logout form.
  2. Register a learning account, sign in and observe the greeting. Use a strong learning password accepted by the built-in validators.
  3. Sign out with the button. Use a separate browser profile to create a second test account for the next lesson.

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.

shop/accounts.py

Create normal customer accounts using Django’s validated form.

shop/accounts.py
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})

Read the code

  1. UserCreationForm checks matching passwords and password rules, and saves a hash rather than plain text.
  2. A new account is not staff. Signup redirects to login instead of silently enabling admin privileges.

config/urls.py

Mount built-in login/logout views and the custom registration page.

config/urls.py
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")),
]

Read the code

  1. Class-based auth views become callable views through as_view. LoginView uses registration/login.html by convention.
  2. LogoutView expects a POST in this Django version. Do not replace the CSRF-protected logout form with a GET link.

templates/base.html

Provide the shared HTML document, navigation and content slots.

templates/base.html
{% 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>

Read the code

  1. extends in a child template reuses this document; block content is where that child supplies its page.
  2. url resolves named routes and static builds the asset URL. These are server-side template tags, not browser JavaScript.
  3. Messages report the outcome after a redirect. Once authentication is added, logout uses a CSRF-protected POST form.

templates/registration/login.html

Render the built-in authentication form and optional return path.

templates/registration/login.html
{% 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 %}

Read the code

  1. LoginView validates credentials and establishes the session. It also checks allowed redirect targets; do not replace this with an unchecked redirect to user input.
  2. The template does not handle or store passwords itself.

templates/registration/signup.html

Display registration fields and password feedback.

templates/registration/signup.html
{% extends "base.html" %}
{% block content %}<h1>Create an account</h1><form method="post">{% csrf_token %}{{ form.as_p }}<button>Register</button></form>{% endblock %}

Read the code

  1. The form explains invalid passwords and mismatched confirmation. Errors are generated by the server, not a custom JavaScript-only check.

4. Run it and check your result

  • A new account can register, sign in and sign out.
  • Invalid credentials show feedback and normal signup does not grant admin access.

5. Predict, change and observe

Try opening /admin/ with your newly registered customer.

Compare your prediction with the expected result

What you should observe

The account does not gain staff access.

Why it happens

UserCreationForm creates a normal user. Staff status and model permissions are separate from having valid credentials.

6. Troubleshoot with evidence

A common mistake

Do not put a password in localStorage or a plain model field. Use Django’s authentication APIs.

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.

Login succeeds but redirects to a missing page

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.

7. Practice and explain it back

Your independent task

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.

Is a session cookie the user’s password?

No. It identifies server-side session state. Protecting it still matters because possession can let someone act as the signed-in visitor.

Does registration make a private task list?

No. It establishes accounts. The next lesson must filter reads and writes by the authenticated owner.