Django
How does Django match a URL to a view?
Short Answer
It walks urlpatterns from top to bottom and stops at the first pattern that matches the requested path — there is no scoring and no notion of a "more specific" route, so order is the whole ranking. Each path() string may contain <converter:name> placeholders; the converter supplies a small regex that decides what that segment accepts, and converts the captured text into a Python value that arrives as a keyword argument to the view. Matching sees only the path, never the query string or the HTTP method. The same table runs backwards through reverse(), which builds a URL from a route's name and arguments.
How It Works
urlpatterns is an ordered list. When a request arrives, Django strips the leading slash and tries each entry in sequence; the first one whose pattern consumes the entire remaining path wins, and its view is called. Nothing later in the list is consulted. This is why a broad pattern placed above a narrow one silently swallows it — the resolver never reaches the narrow route to discover it was a better fit.
A path() route is a literal string with optional placeholders written <converter:name>. A converter is a small object with three parts: a regex fragment that says what it will match, to_python which turns the captured string into a Python value, and to_url which turns a value back into a string for reverse(). Five converters ship built in:
str— any characters except/, the default when you write<name>int— one or more digits, arriving in the view as anintslug— letters, digits, hyphens, underscoresuuid— a hyphenated UUID, arriving as aUUIDpath— any characters including/, so it can swallow a multi-segment tail
That / boundary is the one to keep in mind. str stops at a slash, which is what keeps a route confined to a single segment; path does not, which is what lets one route capture 2026/03/eu-west.csv in a single argument.
Converters do real work rather than just matching. <int:shipment_id> hands the view the integer 4471, not the string "4471", so the view needs no parsing and no validation of that shape — a request whose segment is not digits never reaches it, failing the match instead. This is also why the same converter can reject a bad value when building a URL, not only when parsing one.
include() splices one urlconf into another: the prefix matched so far is removed, and the included patterns see only the remainder. reverse() and the {% url %} template tag run the table in the opposite direction, looking a route up by its name= and filling its placeholders — which is what makes route names, rather than hardcoded strings, the stable reference to a URL.
Seeing It Run
These steps share two files. Create bootstrap.py and routes.py as shown in the first step, then replace main.py for each later step. Run with:
python3 main.py
First match wins, and the converter decides the type
The route table, and what four different paths resolve to. resolve() performs exactly the lookup a real request performs, without needing a server.
# bootstrap.py
import django
from django.conf import settings
settings.configure(DEBUG=True, ROOT_URLCONF="routes", ALLOWED_HOSTS=["*"])
django.setup()
# routes.py
from django.http import HttpResponse
from django.urls import path
def dock_board(request, dock):
return HttpResponse(dock)
def shipment_detail(request, shipment_id):
return HttpResponse(shipment_id)
def manifest_file(request, filepath):
return HttpResponse(filepath)
urlpatterns = [
path("docks/<slug:dock>/", dock_board, name="dock-board"),
path("shipments/<int:shipment_id>/", shipment_detail, name="shipment-detail"),
path("manifests/<path:filepath>", manifest_file, name="manifest-file"),
]
# main.py
import bootstrap # noqa: F401
from django.urls import Resolver404, resolve
requested = [
"/docks/dock-7/",
"/shipments/4471/",
"/manifests/2026/03/eu-west.csv",
"/shipments/SHP-4471/",
]
for url in requested:
try:
match = resolve(url)
argument = next(iter(match.kwargs.items()))
print(f"{url:32} -> {match.func.__name__:16} {argument[0]}={argument[1]!r} ({type(argument[1]).__name__})")
except Resolver404:
print(f"{url:32} -> no pattern matched")
/docks/dock-7/ -> dock_board dock='dock-7' (str)
/shipments/4471/ -> shipment_detail shipment_id=4471 (int)
/manifests/2026/03/eu-west.csv -> manifest_file filepath='2026/03/eu-west.csv' (str)
/shipments/SHP-4471/ -> no pattern matched
Three things are visible at once. shipment_id arrives as an int — the converter parsed it, so the view never sees "4471". The path converter captured 2026/03/eu-west.csv including both slashes, which str or slug would have refused. And /shipments/SHP-4471/ matches nothing: <int:…> requires digits, so rather than calling the view with a bad value, Django reports that no route matched and the request becomes a 404.
Try it: Add "/shipments/4471" to the list, without the trailing slash. In a browser such an address usually reaches the page; what does resolve() say? no pattern matched. The pattern ends with /, and matching is exact. The redirect you see in a browser is done by CommonMiddleware (APPEND_SLASH), after resolution has failed; the resolver itself forgives nothing.
Order is the only ranking
Replace main.py. Two route tables holding the same two patterns, differing only in sequence, resolving the same URL.
# main.py
import bootstrap # noqa: F401
from django.http import HttpResponse
from django.urls import path, resolve
def export_csv(request):
return HttpResponse("export")
def shipment_detail(request, reference):
return HttpResponse(reference)
catch_all_first = (
path("shipments/<str:reference>/", shipment_detail),
path("shipments/export/", export_csv),
)
literal_first = (
path("shipments/export/", export_csv),
path("shipments/<str:reference>/", shipment_detail),
)
for label, urlconf in [("catch-all first", catch_all_first), ("literal first ", literal_first)]:
match = resolve("/shipments/export/", urlconf=urlconf)
print(f"{label} -> {match.func.__name__:16} {match.kwargs}")
catch-all first -> shipment_detail {'reference': 'export'}
literal first -> export_csv {}
With the catch-all first, /shipments/export/ is handled by shipment_detail with reference='export' — a shipment lookup for a reference that does not exist, which surfaces as a confusing 404 from inside the view rather than a routing problem. Nothing is malformed; <str:reference> legitimately matches the text export, and the resolver stops there without ever seeing the literal route below. Put fixed segments above patterns that could also match them. resolve() accepts a urlconf argument, which is what allows both tables to be compared in one program; in a project this list is urlpatterns in urls.py.
The same table, backwards
Replace main.py. reverse() turns a route name and its arguments into a URL, and applies the same converters while doing it.
# main.py
import bootstrap # noqa: F401
from django.urls import NoReverseMatch, reverse
print("shipment-detail:", reverse("shipment-detail", kwargs={"shipment_id": 4471}))
print("dock-board :", reverse("dock-board", kwargs={"dock": "dock-7"}))
print("manifest-file :", reverse("manifest-file", kwargs={"filepath": "2026/03/eu-west.csv"}))
try:
reverse("shipment-detail", kwargs={"shipment_id": "SHP-4471"})
except NoReverseMatch:
print("int converter refuses a non-numeric value: NoReverseMatch")
shipment-detail: /shipments/4471/
dock-board : /docks/dock-7/
manifest-file : /manifests/2026/03/eu-west.csv
int converter refuses a non-numeric value: NoReverseMatch
Each URL is rebuilt from the name given in path(..., name=...), so changing shipments/ to consignments/ in routes.py updates every generated link without touching the code that generates them. The last line shows the converter working in the other direction: <int:shipment_id> will not accept "SHP-4471", so reverse() raises rather than emitting a URL that could never be matched back. A converter is a two-way contract, not a parsing convenience.
Try it: Add print("digits as str :", reverse("shipment-detail", kwargs={"shipment_id": "4471"})). The value is a string and the converter is int; an exception or a URL? It prints /shipments/4471/. reverse() does not check the Python type of the value: it turns it into text and tests whether the text matches the converter's pattern. "4471" passes, "SHP-4471" does not.
Edge Cases and Gotchas
- The query string is not routed.
?page=2never participates in matching and never becomes a view argument; read it fromrequest.GET. The same goes for the HTTP method — one route serves every verb, and the view decides. - A missing trailing slash is a different path. With
APPEND_SLASHenabled and the URL not matching, Django redirects/docks/dock-7to/docks/dock-7/rather than matching it directly. Be consistent about trailing slashes across a project. re_path()is for whatpath()cannot express. Patterns needing alternation, optional segments, or a bounded character count still need a regex, where captured groups arrive as strings unless you convert them yourself.- Route names collide silently. Two routes with the same
name=are both valid, andreverse()returns the last one registered. Namespace included urlconfs withapp_nameand reverse them as"depot:shipment-detail". - Custom converters are small classes. Define
regex,to_python, andto_url, register withregister_converter(), and a domain type like a shipment reference can be validated in the route rather than in every view.
Summary
Routing is a linear scan of an ordered list, stopping at the first pattern that consumes the whole path. Converters decide what each placeholder accepts and what Python type the view receives, and they apply in reverse too when reverse() builds a URL from a route name.
urlpatternsis tried top to bottom and the first full match wins; a broad pattern above a narrow one prevents the narrow one from ever being reached.<int:name>delivers anintto the view and rejects non-digit segments at the routing stage, so the view never validates that shape.strandslugstop at/whilepathcrosses it, which is what lets a single placeholder capture a multi-segment tail.- Only the path is matched — the query string and the HTTP method play no part and are read inside the view.
reverse()and{% url %}run the same table backwards by route name, and raiseNoReverseMatchwhen an argument fails its converter.