Skip to content
Kuza Ndoto Academy

URL Routing

IntermediateChapter 2 · Page 7 of 234 min readUpdated 15 Nov 2026

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

  1. Django reads the ROOT_URLCONF setting (here "campus.urls") and loads urlpatterns from that module.
  2. It strips the domain and leading slash, so http://127.0.0.1:8000/events/2/ becomes events/2/.
  3. It tries each pattern in order and stops at the first match.
  4. It calls the matching view, passing the request plus any values captured from the URL.
  5. 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 visitedView calledArguments
/events/event_listnone
/events/2/event_detailpk=2
/events/archive/2026/11/archiveyear=2026, month=11
/events/hackathon/none: 404int doesn't match letters

Visiting /events/archive/2026/11/ shows:

Events from 11/2026
/events/2/ campus/urls.py admin/ no match events/ include() checked top to bottom 2/ events/urls.py "" (empty) no match <int:pk>/ match, pk=2 archive/... not tried event_detail(request, pk=2)
Figure 1. 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.

ConverterMatchesExample
strAny text except / (the default if you leave the converter out)<str:username>
intZero or a positive whole number, passed as int<int:pk>
slugLetters, numbers, hyphens and underscores<slug:slug> for campus-hackathon
uuidA UUID, passed as a uuid.UUID<uuid:ticket_id>
pathAny 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.

Tip

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".

Common mistake

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.

Common mistake

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

  • urlpatterns is checked top to bottom; the first match wins.
  • Use include() so each app owns its URLs, and set app_name for 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.
Up next · URLs & ViewsClass-Based ViewsReusable views for common pages.
→

Tip: use the ← and → keys to move between pages.