Django Login and Logout
Django’s authentication views handle common login form and redirect behaviour. Keep logout as a deliberate POST action with CSRF protection.
How it works
The project’s base template renders a POST logout form when a user is authenticated and a login link otherwise. LoginView checks whether a next destination is allowed rather than blindly redirecting to arbitrary external input. The test client can force_login for tests about post-login behaviour; that bypasses password checking and must not be described as a credential test. Use authenticate or a real login POST when credentials are the feature under review.
Run in the supplied local Django project
This lesson uses Django 5.2.18 LTS with Python 3.12. Download the source downloader and run node download-project.mjs http://127.0.0.1:8000 with Node 22 while previewing locally. It creates a new bhylu-django-lab folder and refuses to overwrite an existing one. After deployment, the default base is bhylu.com; until then use your local preview URL.
Inside that new folder, create a virtual environment, install requirements.txt and run the complete lesson file shown below. Every lesson creates a fresh in-memory SQLite database and temporary upload storage. It does not edit the interactive lab’s db.sqlite3 or Bhylu’s database. The visible listing below is the lesson’s core code; its complete downloaded file includes the shared bootstrap.
Django does not run in Bhylu’s current browser playground. No Apache, MySQL or global PHP configuration change is needed. See the setup lesson for the full project and commands.
Example
Run .venv\Scripts\python.exe lessons\login-logout.py from the downloaded project root. Download the complete lesson file; keep it under lessons/. The project’s shared models, forms, views and fixture are prerequisites, not a hidden online runtime.
from django.contrib.auth import get_user_model
client = Client()
client.force_login(get_user_model().objects.get(username="alex"))
print(client.get("/accounts/logout/").status_code)
print(client.post("/accounts/logout/").status_code)
print("_auth_user_id" in client.session)
Expected result
405 302 False
GET is rejected, the POST redirects and the authenticated session identifier is removed. A later real HTTP test uses the actual token-bearing form. The public workshop list remains readable after logout.
Use Django’s versioned official documentation for exact API contracts and the deployment checklist before a separate release.