Skip to the workspace
Pebellslearn by building
The Request–Response Flow  ›  Lesson

URL Patterns

URL patterns 12 minA URL pattern pairs a route string with a view, and Django walks the patterns in order, calling the first view whose route matches the requested path.

django / URL Patterns

Explore each scene at your own pace.

01 · The rule

The rule

URL Patterns

A request has reached Django. Before any of your code runs, Django must decide which view will answer. It does this with a list of URL patterns, and the rules it follows are few and strict. Knowing them is the difference between "my page is a 404 and I don't know why" and a fix in ten seconds.

The rule

Top to bottom, first match wins, and the path is all it sees.

Here is the whole journey of a request, the map for this section:

browser → server → middleware (in) → URL patterns → view → middleware (out) → browser

The URL patterns step looks only at the path: no domain, no ?query, no leading slash. Each entry is a path():

# recipes/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("", views.recipe_list),                 # /recipes/
    path("quick/", views.quick_recipes),         # /recipes/quick/
    path("<slug:slug>/", views.recipe_detail),   # /recipes/tomato-soup/
]

path(route, view) takes the route string, then the view to call. It can also take a name, which a later lesson puts to work. The part in angle brackets captures a piece of the URL and passes it to the view; that is the subject of the next lesson.

A route must match the whole remaining path. quick/ matches quick/ but not quick/extra/.

Trailing slashes are a Django convention. If someone types /recipes/quick without the slash, nothing matches; with the default APPEND_SLASH = True, Django redirects them to /recipes/quick/, which does.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.