Django · Chapter 2 of 8
Django URLs and views: converters, query strings, JSON
13 min study · Examples checked with Django 6.1 on Python 3.14 ·
The first chapter mapped one URL to one view. A real site needs URLs with parameters (/lessons/3/), optional filters in the query string (?level=beginner), different kinds of responses, redirects and a little state kept in the browser. This chapter extends the catalog app with all of these. The lessons are still a dictionary in code; chapter 4 moves them into the database, and the views will hardly change.
URL patterns with converters
Replace catalog/urls.py:
from django.urls import path
from . import views
app_name = "catalog"
urlpatterns = [
path("", views.home, name="home"),
path("lessons/", views.lesson_list, name="lessons"),
path("lessons/<int:lesson_id>/", views.lesson_detail, name="lesson"),
path("lesson.php/<int:lesson_id>/", views.old_lesson_url),
path("preferences/level/<slug:level>/", views.set_level, name="set-level"),
]
<int:lesson_id> matches digits only and passes them to the view as an int argument called lesson_id. Other converters are str (anything except /, the default), slug (letters, digits, - and _), uuid and path (which includes slashes). A path like /lessons/abc/ doesn’t match the int pattern at all, so Django tries the following patterns and ends with a 404. Unlike FastAPI’s 422, it never reaches the view. For patterns that converters can’t express, re_path accepts a regular expression.
Patterns end with a slash by convention. With the default APPEND_SLASH setting, a request for /lessons/2 is answered with a 301 redirect to /lessons/2/, so both spellings work for browsers, but only the canonical one serves content.
The views
Replace catalog/views.py:
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.views.decorators.http import require_GET, require_POST
LESSONS = {
1: {"title": "Variables", "minutes": 20, "level": "beginner"},
2: {"title": "Loops", "minutes": 25, "level": "beginner"},
3: {"title": "Decorators", "minutes": 40, "level": "advanced"},
}
@require_GET
def home(request):
return HttpResponse("<h1>Study catalog</h1><p>Lessons will appear here.</p>")
@require_GET
def lesson_list(request):
level = request.GET.get("level") or request.COOKIES.get("level")
try:
limit = min(int(request.GET.get("limit", 10)), 50)
except ValueError:
return JsonResponse({"error": "limit must be a whole number"}, status=400)
rows = [
{"id": pk, **data, "url": reverse("catalog:lesson", args=[pk])}
for pk, data in LESSONS.items()
if level is None or data["level"] == level
]
return JsonResponse({"lessons": rows[:limit]})
@require_GET
def lesson_detail(request, lesson_id):
lesson = LESSONS.get(lesson_id)
if lesson is None:
raise Http404("No such lesson")
return JsonResponse({"id": lesson_id, **lesson})
def old_lesson_url(request, lesson_id):
return redirect("catalog:lesson", lesson_id=lesson_id, permanent=True)
@require_POST
def set_level(request, level):
response = redirect("catalog:lessons")
response.set_cookie("level", level, max_age=30 * 24 * 3600, httponly=True, samesite="Lax")
return response
These are the responses from Django’s test client:
GET /lessons/?level=beginner&limit=1 -> 200
{"lessons": [{"id": 1, "title": "Variables", "minutes": 20, "level": "beginner", "url": "/lessons/1/"}]}
GET /lessons/2/ -> 200 {"id": 2, "title": "Loops", "minutes": 25, "level": "beginner"}
GET /lessons/9/ -> 404
GET /lessons/?limit=x -> 400 {"error": "limit must be a whole number"}
GET /lesson.php/3/ -> 301 Location: /lessons/3/
POST /lessons/ -> 405 Allow: GET
Reading the request
request.GET holds the query string as a QueryDict, which behaves like a dictionary of strings; request.GET.get("level") returns None when the parameter is missing, and getlist("tag") returns every value of a repeated parameter. Everything in it is text and nothing is validated for you, so the view converts limit itself and answers 400 if that fails, and caps it at 50 so nobody can request a giant page. Chapter 7 shows how Django forms do this validation more systematically.
request.POST holds submitted form fields, request.COOKIES the cookies, request.headers the headers (case-insensitive: request.headers["Accept-Language"]), request.method the HTTP method, and request.user the logged-in user once authentication is in use. JSON sent by API clients arrives raw in request.body, to be parsed with json.loads.
Responses: HTML, JSON and errors
HttpResponse sends text, HTML by default. JsonResponse serializes a dictionary and sets Content-Type: application/json; pass status=400 or another code when the request was wrong. To signal a missing object, raise Http404: Django renders its 404 page, a detailed one while DEBUG is on and a plain one, or your own 404.html template, in production. Chapter 4’s get_object_or_404 does the lookup and the raise in one call.
The require_GET and require_POST decorators reject other methods with 405 and an Allow header. That matters more than it seems: a view that changes data must not respond to GET, because browsers prefetch links, crawlers follow them and GET requests can be triggered from other websites with a simple image tag. For the full Django REST API toolkit (serializers, authentication, browsable API), the Django REST Framework package builds on these same views.
Redirects and reverse
reverse("catalog:lesson", args=[3]) builds the URL for a named pattern, /lessons/3/. redirect("catalog:lesson", lesson_id=3) does the same and returns a redirect response. Building URLs from names means a pattern can change in one place without breaking links. The old lesson.php address uses permanent=True for a 301, which tells browsers and search engines the move is final. redirect without it sends a 302.
Cookies
set_level stores the reader’s preferred level in a cookie for 30 days, and lesson_list uses it when no level parameter is given:
POST /preferences/level/advanced/ -> 302 Location: /lessons/
Set-Cookie: level=advanced; expires=...; HttpOnly; Max-Age=2592000; Path=/; SameSite=Lax
HttpOnly keeps JavaScript from reading the cookie and SameSite=Lax stops other sites’ forms from sending it. The view only accepts POST, since it changes state, and like every Django POST view it is protected by CSRF middleware: a browser request without a valid CSRF token gets 403, and forms include the token with {% csrf_token %} (chapter 7). The test client skips that check by default, which is why the request above succeeded. Cookies come from the client, so a forged level=anything must simply match no lessons rather than break the page. For data that must not be tampered with, such as a logged-in user’s identity, Django’s sessions keep the data on the server and put only a signed session ID in the cookie.
Practice
Add GET /lessons/<slug:level>/count/ that returns {"level": ..., "count": ...} and a 404 for levels that have no lessons, and make lesson_list accept repeated level parameters (?level=beginner&level=advanced).
Answer check: the count view filters LESSONS.values() and raises Http404 when the count is 0. Put its pattern before or after lessons/<int:lesson_id>/; it doesn’t matter here, because beginner never matches int. For repeated parameters use request.GET.getlist("level") and keep a lesson when the list is empty or contains its level.
Summary
URL patterns capture typed values with converters and send everything else to 404; trailing slashes are added by redirect. Views read request.GET, POST, COOKIES and headers, validate what they read, and return HttpResponse, JsonResponse or raise Http404. Restrict methods with require_GET/require_POST, build URLs with reverse and redirect, and treat cookies as untrusted input.