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.