urls.py — The Site's Table of Contents
A request arrives for /recipes/. Out of all the code in the project, how does Django know which function should answer? It looks it up in a list, like the table of contents of a book. That list lives in urls.py, and settings.ROOT_URLCONF says which one to start with.
The rule
urlpatternsmaps paths to views;include()hands a branch to an app.
The project's cookbook/urls.py starts like this:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("recipes/", include("recipes.urls")),
]Each path() pairs a route (a piece of URL) with what should handle it. The route has no leading slash, and no domain or ?query part.
include("recipes.urls") says: "anything starting with recipes/ is the recipes app's business". The app gets its own file, which you create:
# recipes/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.recipe_list), # /recipes/
path("quick/", views.quick_recipes), # /recipes/quick/
]Django checks patterns top to bottom and stops at the first match. When it matches through include(), it cuts off the part already matched and passes the rest to the app's list.
Why split at all? The project file stays a short table of contents, and the app carries its own URLs wherever it goes. You could mount the same app at cookbook/ or food/ by changing one line.
The shortcut
To trace a URL, peel it left to right: remove the leading /, find the project pattern that matches the start, cut that part off, and repeat inside the included file until something calls a view.
Drop the leading slash
Django works with
recipes/quick/.
If nothing matches anywhere, the answer is a 404 Not Found. With DEBUG = True, that 404 page helpfully lists every pattern Django tried.
Drills
Answer fast — trust the rule.
Which route string is written correctly for /about/?
What does include("recipes.urls") do?
Two patterns could both match a path. Which one wins?
With the files above, which view handles /recipes/?
Remember
urlpatternsmaps paths to views;include()hands a branch to an app.- Peel the URL left to right, first match wins at every level.
- Trap: a leading slash in a route never matches.
