URLs, Views and Returning Responses

URLs, Views and Returning Responses in Django: Picture the parcel-sorting hall of a regional depot.

The Analogy: A Parcel Sorting Conveyor with Diverter Gates

Picture the parcel-sorting hall of a regional depot. A single conveyor belt runs the length of the room, and every parcel that enters the building is placed on it at one end. Ranged along the belt, in a fixed physical order, is a row of diverter gates. Each gate is a hinged arm that can swing out to knock a parcel off the belt and down a chute into the bin behind it. A parcel rides the belt past the gates one at a time, in the order they are bolted to the floor -- there is no central computer deciding where each parcel goes, only this line of gates each getting its turn.

Each gate is set up to recognise one kind of shipping label. The first gate might be tuned to labels that read exactly "RETURNS"; the next to labels of the form "AISLE-<number>"; another to a plain "OVERFLOW". As a parcel reaches a gate, the gate compares the label against its own template. The very first gate whose template matches swings out, and the parcel leaves the belt immediately -- it never reaches any gate further down, and nothing downstream gets a second opinion. This first-match-wins rule, evaluated in belt order, is exactly how Django walks its list of URL patterns: top to bottom, and the first pattern that matches the path is the one that handles the request.

Some gates are fussier than a plain string comparison. The "AISLE-<number>" gate has a little scanner that insists the part after the dash be all digits. A label reading "AISLE-42" matches and is diverted; a label reading "AISLE-BULK" is inspected, fails the digits-only check, and is left on the belt to continue to the next gate as though this gate had never looked at it. That scanner is a path converter: the "<int:pk>" segment in a Django route matches only a run of digits, so a path segment that is not numeric slides straight past that pattern to whatever comes next.

Now suppose a maintenance crew bolts a wide catch-all gate -- one that matches any label at all -- near the front of the belt, ahead of the specific gates. Every parcel now hits that gate first, matches, and is swept into the overflow bin. The specific gates downstream still stand there, perfectly configured, but no parcel ever reaches them. Nothing jams and no alarm sounds; parcels simply pile up in the wrong bin while the crew swears the specific gates are "installed". That is the single most common URL bug in Django: a broad pattern placed above a narrow one. Because matching stops at the first hit, the narrow route becomes dead code, and the only symptom is a view quietly serving the wrong response to a URL you were sure you had wired up.


Syntax or Core Structure

A Django URLconf is an ordered list of path() calls. Each pairs a string pattern with a view callable, and Django tries them in order until one matches. To see the mechanics without a running server, here is the resolver reduced to a plain-Python REPL: a list of routes, a match() that understands one converter (<int>, digits only), and a resolve() that returns the first hit. This is the logic Django's own resolver runs, stripped of everything but the ordering and the converter check.

# A URL resolver, reduced to a plain REPL.
# Django scans patterns top to bottom; the FIRST match wins.
# The <int> converter also VALIDATES: a non-digit segment does not match it.

def match(pattern, path):
    pseg = [s for s in pattern.split("/") if s]
    tseg = [s for s in path.split("/") if s]
    if len(pseg) != len(tseg):
        return None
    captured = []
    for p, t in zip(pseg, tseg):
        if p == "<int>":
            if not t.isdigit():
                return None          # converter rejects it: fall through
            captured.append(int(t))
        elif p != t:
            return None
    return captured                  # [] means matched with no capture

routes = [
    ("/products/",       "product-list"),
    ("/products/<int>/", "product-detail"),
    ("/products/new/",   "product-new"),
]

def resolve(path):
    for pattern, name in routes:
        captured = match(pattern, path)
        if captured is not None:
            return name + " pk=" + str(captured[0]) if captured else name
    return "404"

for path in ["/products/", "/products/42/", "/products/new/", "/products/abc/"]:
    print(resolve(path))

Read the route table top to bottom. /products/ matches the first route with no capture. /products/42/ fails the first route (segment counts differ) and hits the <int> route, capturing 42. The interesting case is /products/new/: it reaches the <int> route, but "new" is not all digits, so the converter rejects it and matching continues to the literal product-new route below. That is why a numeric-detail route can sit safely above a /new/ route -- the converter, not the ordering, keeps them apart. Finally /products/abc/ matches nothing and falls through to a 404.

Output:

product-list
product-detail pk=42
product-new
404

The lesson to carry from this block: ordering decides which patterns even get consulted, and converters decide whether a consulted pattern accepts the segment. Get either wrong and Django will not raise an error -- it will simply return whatever the first accepting route produces, which is why URL bugs surface as wrong pages rather than exceptions.


Technical Depth: Converters, Object Lookup and HTTP Methods

A view is just a callable that takes a request and returns a response. Everything interesting happens in three places: how the URL captures values, how the view turns a captured id into an object (or a 404), and how it decides what to do based on the request method. We take each in turn.

Path converters and what they capture

Django ships a small set of built-in converters. The converter both restricts which paths match and controls the Python type your view receives, so choosing the right one removes a whole class of validation code from the view body.

ConverterWhat it matchesCaptured Python type
strany non-empty text without a slashstr
intzero or a positive integerint
slugASCII letters, digits, hyphen, underscorestr
uuida formatted UUID stringUUID
pathany non-empty text including slashesstr

The default when you write <pk> with no converter is str, which is why <int:pk> matters: it rejects /products/new/ at the URL layer so the view never has to guard against a non-numeric id.

Turning an id into an object, or a 404

The idiom get_object_or_404(Model, pk=pk) looks the row up and raises Http404 if it is missing. Folding an active=True filter into the same call is common -- and has a consequence worth seeing. Here is the lookup as a plain function over an in-memory table:

products = [
    {"id": 1, "name": "pump",  "active": True},
    {"id": 2, "name": "clamp", "active": False},
]

def get_or_404(pk):
    for row in products:
        if row["id"] == pk and row["active"]:
            return row
    return None

def product_detail(pk):
    row = get_or_404(pk)
    return "404" if row is None else "200 " + row["name"]

for pk in [1, 2, 9]:
    print(product_detail(pk))

Output:

200 pump
404
404

Note that pk 2 (clamp) exists but is inactive, and pk 9 does not exist at all -- yet both return an identical 404. Folding the filter into the lookup is convenient, but it erases the distinction between "gone" and "hidden", which matters the day a user reports a link that "used to work".

Branching on the request method

A single URL often serves several methods: GET renders a form, POST processes it. The rule that keeps this safe is that a GET must never change state, and after a successful POST you redirect rather than render, so a browser refresh re-issues the harmless GET instead of re-submitting the form. That pattern is Post/Redirect/Get. Here it is as a pure function:

# GET shows a form; POST creates then redirects (Post/Redirect/Get);
# anything else is 405 Method Not Allowed.
ALLOWED = {"GET", "POST"}

def create_product(method):
    if method not in ALLOWED:
        return "405 method not allowed"
    if method == "GET":
        return "200 form"
    return "302 redirect to /products/"   # POST: create, then redirect

for method in ["GET", "POST", "DELETE"]:
    print(create_product(method))

Output:

200 form
302 redirect to /products/
405 method not allowed

The 302 after a POST is the whole point: the response body is empty and carries a Location header, so the browser fetches the list page afresh and the "are you sure you want to resubmit?" dialog never appears. DELETE is not in the allowed set, so the view returns 405 with an Allow header listing GET and POST -- Django's own require_http_methods decorator and the class-based View.http_method_not_allowed produce exactly this.


Real World Example: Serving a Paginated Catalog and Its Detail Pages

A catalog page rarely shows every product at once; it shows a page of them, with links to the next page, and each item links to a detail page. Django's Paginator handles the slicing and, through get_page(), is deliberately forgiving about bad input. That forgiveness is a feature and a trap at once. The program below is the whole flow -- active-only listing, pagination with clamping, and a detail lookup -- as runnable plain Python so every number is exact.

products = [
    {"id": 1, "name": "pump",  "active": True},
    {"id": 2, "name": "hose",  "active": True},
    {"id": 3, "name": "clamp", "active": True},
    {"id": 4, "name": "valve", "active": False},
    {"id": 5, "name": "gauge", "active": True},
]
PAGE_SIZE = 2

def active_products():
    # materialises every active row in Python (see the flaws below)
    return [r for r in products if r["active"]]

def num_pages(total):
    return (total + PAGE_SIZE - 1) // PAGE_SIZE

def get_page(rows, requested):
    total = num_pages(len(rows))
    try:
        page = int(requested)
    except (TypeError, ValueError):
        page = 1                      # junk -> page 1
    if page < 1:
        page = 1
    if page > total:
        page = total                  # out of range -> last page (clamp)
    start = (page - 1) * PAGE_SIZE
    names = [r["name"] for r in rows[start:start + PAGE_SIZE]]
    return "page " + str(page) + "/" + str(total) + ": " + ",".join(names)

def list_page(requested):
    return get_page(active_products(), requested)

def detail(pk):
    for r in products:
        if r["id"] == pk and r["active"]:
            return "200 " + r["name"]
    return "404"

print(list_page(1))
print(list_page(2))
print(list_page(9))
print(list_page("x"))
print(detail(3))
print(detail(4))

Output:

page 1/2: pump,hose
page 2/2: clamp,gauge
page 2/2: clamp,gauge
page 1/2: pump,hose
200 clamp
404

Walk the pagination first. There are five products but only four are active, and at two per page that is exactly two pages. Page 1 serves pump and hose; page 2 serves clamp and gauge. The inactive valve never appears because active_products() filters it out before slicing, so the page counts are computed over the four visible rows, not the five stored ones -- get that filter order wrong and your page numbers stop matching the rows you actually show.

The third and fourth calls show get_page's forgiveness. Asking for page 9 does not error; it clamps to the last page and serves clamp and gauge again. Asking for page "x" -- the kind of value a template produces when a query-string variable is empty -- is coerced to page 1 and serves pump and hose. Both requests return a normal 200 page, which is precisely why the bugs they hide are so quiet.

The detail calls close the loop. Product 3 (clamp) is active, so detail(3) returns "200 clamp". Product 4 (valve) exists in the table but is inactive, so detail(4) returns 404 -- the same 404 a genuinely missing id would produce. The listing and the detail view agree on which products are visible, which is the property you want, but they express "invisible" only as absence.

Now the flaws, because this code is typical and typical is not the same as correct. First, get_page's clamping means a bookmarked link to page 5 silently shows page 2 forever; the user never learns their bookmark rotted, and neither do you. Second, coercing "x" to page 1 masks a broken query string: a template that builds ?page= with an empty variable serves page 1 on every click, and the page looks fine in every test. Third, the detail view collapses inactive and missing into one 404, so you cannot tell a discontinued product from a bad id in the logs. Fourth and most expensive, active_products() materialises the entire active set into a Python list on every request and then slices it -- fine for five rows, ruinous for fifty thousand, because the database work that pagination exists to avoid (a LIMIT/OFFSET query) is being done in application memory instead. Django's real Paginator over a lazy QuerySet pushes the slice into SQL; a list does not, and the difference is invisible until the table grows.


Common Mistakes

  1. Placing a broad pattern above a specific one. Because matching stops at the first hit, a route like <str:slug>/ sitting above about/ swallows the about request whole. The specific view becomes unreachable and nothing errors -- you just serve the wrong page. Order URLs from most specific to most general.
  1. Reaching for str when you meant int. Writing <pk> or <str:pk> where the id is numeric lets /products/new/ match the detail route and hands your view the string "new". Use <int:pk> so the URL layer rejects non-numeric ids before the view ever runs.
  1. Letting a GET change state. A view that deletes or updates on GET will be triggered by prefetchers, link scanners, and a user's browser history. Confine writes to POST (or DELETE/PUT for APIs) and let GET be safe and repeatable.
  1. Rendering the page after a successful POST. If you return the rendered result instead of a redirect, a browser refresh re-submits the form and creates a duplicate. Always follow a successful POST with a redirect (Post/Redirect/Get) so the refreshed request is a harmless GET.
  1. Hardcoding URLs as string literals. Writing /products/42/ in a template or return redirect("/products/") couples your code to the current path layout. Use named routes with {% url %} and reverse(); then changing the pattern updates every link automatically.
  1. Skipping app namespaces. Without app_name in each app's urls.py, two apps that both name a route "detail" collide, and reverse("detail") resolves to whichever loaded last. Namespace them and call reverse("catalog:detail").
  1. Forgetting the trailing slash convention. Django's default APPEND_SLASH redirects /products to /products/, but only for GET; a slash-less POST gets a 404 instead of a redirect. Define patterns with the trailing slash and generate links with reverse() so they always carry it.
  1. Returning the wrong status or content type. Sending a 200 with an error message in the body, or JSON with a text/html content type, breaks clients that inspect the status line. Return JsonResponse for JSON, set the real status code, and let 404/403/405 mean what they say.
  1. Swallowing Http404 by hand. Wrapping the lookup in try/except Model.DoesNotExist and returning an empty 200 hides missing rows from your monitoring and confuses clients. Prefer get_object_or_404, which returns a real 404, and reserve manual handling for cases that genuinely differ.

Best Practices

  • Name every route and build links with reverse. Give each path() a name=, then use {% url %} in templates and reverse()/redirect() in views. Your URL structure becomes something you can change in one place without hunting for string literals.
  • Namespace URLs per app. Set app_name in each app's urls.py and address routes as app:route. This prevents name collisions as the project grows and makes it obvious which app a link points into.
  • Let converters do your validation. Choose <int:pk>, <slug:slug>, or <uuid:id> so malformed URLs are rejected before the view runs. A view that only ever receives a well-typed id is shorter and harder to break.
  • Keep views thin and single-purpose. A view should map a request to a response and delegate real work to models, forms, and services. Fat views mixing query logic, formatting, and side effects are the hardest code to test and reuse.
  • Use get_object_or_404 for lookups that can miss. It expresses "this row must exist or the URL is wrong" in one line and returns a correct 404, instead of scattering try/except DoesNotExist blocks that each decide the failure mode differently.
  • Always redirect after a successful POST. Return an HttpResponseRedirect (via redirect()) so a refresh cannot resubmit. Render the form again only when validation fails and you need to show errors.
  • Return the most specific response type. JsonResponse for JSON, HttpResponseRedirect for redirects, HttpResponseNotAllowed for bad methods. The right class sets the status and headers correctly so clients can rely on them.
  • Reach for generic class-based views when the shape is standard. ListView and DetailView give you pagination, object lookup, and 404 handling for free; write a function-based view when the logic is genuinely bespoke, not by default.

Practice Exercises

  1. Fix the dead route. Given a URLconf where path("products/<int:pk>/", ...) sits above path("products/new/", ...), explain from the converter rule why /products/new/ still resolves correctly, then construct one reordering that WOULD break it and say which request breaks.
  1. Add a slug converter and a case rule. Extend the plain-Python resolver so a route /tag/<slug>/ captures the slug, and make an uppercase segment like /tag/PUMP/ fail to match (Django's slug converter is lowercase-and-hyphen). Verify /tag/pump/ returns the slug and /tag/PUMP/ returns 404.
  1. Implement Post/Redirect/Get. Write a create(method) function that returns "200 form" for GET, performs a create and returns "302 redirect" for POST, and "405" otherwise. Then add a second POST call and confirm your function would create two rows -- explaining why the redirect, not the function, is what actually prevents the duplicate in a browser.
  1. Distinguish gone from hidden. Modify the detail lookup so a missing id returns 404 but an inactive-but-existing product returns 410 (Gone). Trace detail(3), detail(4), and detail(9) for the catalog in the Real World example and give the three status lines.