Skip to the workspace
Pebellslearn by building
Projects and Apps  ›  Lesson

urls.py — The Site's Table of Contents

urls.py 12 minThe project's urls.py holds a urlpatterns list that maps URL paths to views, and include() hands whole groups of URLs to an app's own urls.py.

django / urls.py — The Site's Table of Contents

Explore each scene at your own pace.

01 · The rule

The rule

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

urlpatterns maps 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.

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