URL Routing
URL routing is how Django decides which view should handle each web address. You describe the addresses your site supports in a list called urlpatterns, and Django matches every incoming request against it.
How Django finds a view
- Django reads the
ROOT_URLCONFsetting (here"campus.urls") and loadsurlpatternsfrom that module. - It strips the domain and leading slash, so
http://127.0.0.1:8000/events/2/becomesevents/2/. - It tries each pattern in order and stops at the first match.
- It calls the matching view, passing the request plus any values captured from the URL.
- If nothing matches, Django returns a 404 response.
path() and include()
path(route, view, name=...) connects one route to one view. include() hands a whole section of the site to another URLconf, usually an app's urls.py. This keeps each app's routes inside the app.
campus/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("events/", include("events.urls")),
]
When a URL starts with events/, Django chops that part off and passes the rest to events/urls.py:
events/urls.py
from django.urls import path
from . import views
app_name = "events"
urlpatterns = [
path("", views.event_list, name="event_list"),
path("<int:pk>/", views.event_detail, name="event_detail"),
path("archive/<int:year>/<int:month>/", views.archive, name="archive"),
]
The archive view receives the captured values as keyword arguments, already converted to integers:
events/views.py
from django.http import HttpResponse
def archive(request, year, month):
return HttpResponse(f"Events from {month}/{year}")
Here's how some addresses are resolved:
| URL visited | View called | Arguments |
|---|---|---|
/events/ | event_list | none |
/events/2/ | event_detail | pk=2 |
/events/archive/2026/11/ | archive | year=2026, month=11 |
/events/hackathon/ | none: 404 | int doesn't match letters |
Visiting /events/archive/2026/11/ shows:
include() strips the matched part (events/) and passes the rest to the app's URLconf. Matching stops at the first pattern that fits.Path converters
The part in angle brackets, <converter:name>, captures a piece of the URL. The converter decides what text matches and what Python type the view receives.
| Converter | Matches | Example |
|---|---|---|
str | Any text except / (the default if you leave the converter out) | <str:username> |
int | Zero or a positive whole number, passed as int | <int:pk> |
slug | Letters, numbers, hyphens and underscores | <slug:slug> for campus-hackathon |
uuid | A UUID, passed as a uuid.UUID | <uuid:ticket_id> |
path | Any text including / | <path:file_path> |
For unusual patterns there is also re_path(), which takes a regular expression, but path() covers almost every real need.
Naming URLs and reversing them
Every pattern above has a name, and app_name = "events" puts them in a namespace. Instead of typing addresses like "/events/2/" by hand, you refer to them by name and let Django build the URL. This is called reversing.
In Python code, use reverse() (or redirect(), which reverses for you). You can try it in python manage.py shell:
>>> from django.urls import reverse
>>> reverse("events:event_list")
'/events/'
>>> reverse("events:event_detail", args=[2])
'/events/2/'
>>> reverse("events:archive", kwargs={"year": 2026, "month": 11})
'/events/archive/2026/11/'
In templates, use the {% url %} tag:
events/templates/events/event_list.html
<a href="{% url 'events:event_detail' event.id %}">{{ event.title }}</a>
Now if you ever change events/ to whats-on/ in campus/urls.py, every link on the site updates automatically.
Namespaces matter once you have several apps. Two apps might both have a URL named detail; "events:detail" and "blog:detail" keep them apart.
Trailing slashes and order
Django's convention is to end routes with a slash: "events/", not "events". With the default APPEND_SLASH = True setting, a visit to /events is redirected to /events/.
Because Django stops at the first match, put specific patterns before general ones:
urlpatterns = [
path("new/", views.event_create, name="event_create"), # specific first
path("<str:slug>/", views.event_by_slug, name="event_by_slug"), # catches anything
]
If these two were swapped, /events/new/ would be captured by the str pattern with slug="new".
Starting a route with a slash, as in path("/events/", ...). Django removes the leading slash before matching, so this pattern never matches. Running the server shows a warning (urls.W002) about it.
Writing views.event_list() with brackets in path(). That calls the function immediately instead of passing it to Django. Pass the function itself: views.event_list.
When a URL doesn't match and DEBUG is True, Django's 404 page lists every pattern it tried, in order. Read it carefully: it usually shows exactly why your URL didn't match.
Key points
urlpatternsis checked top to bottom; the first match wins.- Use
include()so each app owns its URLs, and setapp_namefor a namespace. - Converters such as
<int:pk>and<slug:slug>capture and convert parts of the URL. - Name every URL and build links with
reverse()and{% url %}, never by hand.
Tip: use the ← and → keys to move between pages.
