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) → browserThe 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.
The shortcut
Specific above general. Fixed routes like quick/ go above routes that capture anything, like <slug:slug>/. Otherwise the general pattern swallows the specific URL before its own pattern is ever reached.
Project level
recipes/matches throughinclude(), leavingquick/.
When nothing matches, the response is 404. With DEBUG = True the error page lists every pattern that was tried, in order, which is the fastest way to spot an ordering bug.
Drills
Answer fast — trust the rule.
For the request https://cookbook.example.com/recipes/?sort=new, what does URL matching see?
A pattern list has <slug:slug>/ first and new/ second. What happens at /recipes/new/?
With APPEND_SLASH = True, what happens at /recipes/quick if only quick/ exists?
Does the route quick/ match the remaining path quick/extra/?
Remember
- Top to bottom, first match wins, and only the path is matched.
- Specific routes above general ones.
- Trap: a capturing pattern placed too high swallows fixed URLs.
