Matching a URL to a View

What this is. urlpatterns is a list of patterns checked top to bottom. The first one that matches wins, and its view is called.

Angle brackets capture part of the address and pass it to the view as an argument.

Routing across two files

Project

# project urls.py
urlpatterns = [
  path("admin/", admin.site.urls),
  path("", include("posts.urls")),
]

App

# posts/urls.py
app_name = "posts"

urlpatterns = [
  path("", views.index,
    name="index"),
  path("post/<int:pk>/",
    views.detail, name="detail"),
]
Compare → include() keeps each app's routes inside the app. Without it every route in the site ends up in one file that nobody wants to open.

Converters do real work. <int:pk> matches digits only and hands the view an actual integer. <slug:slug> matches letters, numbers, hyphens and underscores. <str:name> matches anything except a slash.

Choosing int means a request for /post/banana/ never reaches your view at all: it simply does not match, and Django returns a 404 without you writing a check.

✦ Order matters, and it bites quietly

Patterns are checked in order and the first match wins. A broad pattern placed above a specific one swallows it, and the specific view is never called. There is no warning, because both patterns are perfectly valid.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Named URLs →
← Back