Protecting Django Views
Protecting a view means only logged-in readers can open it. Guests are sent to the login page instead.
Mark the view
The login_required line sits above the view. It marks the view as logged-in only.
@login_required
def secret(request):
return HttpResponse("Secret page")Ask without logging in
A guest gets a redirect, not the page. The prints show the status and the redirect address.
client = Client()
print(client.get("/secret").status_code)
print(client.get("/secret")["Location"])Log in, then ask again
The test client logs in as sana first. The same address now shows the secret page.
client.login(username="sana", password="secret123")
print(client.get("/secret").content.decode())Example
import django
from django.conf import settings
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
INSTALLED_APPS=[
"django.contrib.contenttypes",
"django.contrib.auth",
"django.contrib.sessions",
],
MIDDLEWARE=[
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
LOGIN_URL="/login/",
)
django.setup()
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.management import call_command
from django.http import HttpResponse
from django.urls import path
from django.test import Client
@login_required
def secret(request):
return HttpResponse("Secret page")
urlpatterns = [path("secret", secret), path("login/", lambda request: HttpResponse("Show the login form"))]
call_command("migrate", verbosity=0)
User.objects.create_user("sana", password="secret123")
client = Client()
print(client.get("/secret").status_code)
print(client.get("/secret")["Location"])
client.login(username="sana", password="secret123")
print(client.get("/secret").content.decode())
print(client.get("/secret").status_code)Key points
- @login_required marks a view as logged-in only.
- A guest asking for the view gets a redirect.
- The redirect points at the login page.
- A logged-in reader sees the page as normal.
- LOGIN_URL sets the address of the login page.
- A protected view opens only for logged-in readers.
In this example, the setup lines configure Django. The program runs migrations first and makes a user named sana. The login_required line marks the secret view as logged-in only. A guest gets a 302 redirect to the login page. The test client logs in as sana and asks again. The prints show the redirect status, the login address, the secret page, and the 200 status.
Note
The redirect carries a next value with the wanted address.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens when a guest opens a view marked with @login_required?