The Django URL Dispatcher is a mechanism that routes incoming HTTP requests to the appropriate view function or class based on pattern matching of the requested URL.
When a request hits a Django server, it needs to know what code should handle it. The URL dispatcher is like a receptionist mapping the URL path (e.g., /students/15) to a specific python function (a view) that knows how to generate the response.
- Django looks at the
ROOT_URLCONFsetting to find the rooturls.py. - It iterates through the
urlpatternslist in order. - It tries to match the requested URL against each pattern (using
path()orre_path()). - Upon the first match, it imports and calls the associated view function, passing the request and any captured URL parameters.
graph LR A[Incoming Request: /hello/] --> B(URL Dispatcher) B -->|Matches /hello/| C(View: hello) B -->|Matches /about/| D(View: about)
Think of the URL Dispatcher as a switchboard operator or a mail sorter. It looks at the address on the envelope (the URL) and routes it to the correct department (the view) to be processed.
from django.urls import path
from . import views
urlpatterns = [
path("hello/", views.hello),
]- Evaluated top-to-bottom: The first matching pattern wins.
- Supports path converters: Can capture variables from URLs (e.g.,
<int:id>). - Supports namespaces: Allows apps to have isolated URL names.
- Built from: Django Web Framework — core component of the framework.
- Builds into: Django View — routes requests to views.
- Related: Django Request-Response Lifecycle — it is the first step in the lifecycle.
- Related: Django Project — configured at the project level.
- Forgetting the trailing slash can cause unexpected 404s depending on the
APPEND_SLASHsetting. - Overlapping patterns: A broad pattern at the top might accidentally catch URLs meant for patterns below it.