← Back to Django, page 1

django-0006 · Easy fresher

How does URL routing work in Django? Explain path(), converters, include() and reverse().

Django matches the request path against urlpatterns in order. path() takes a route string, a view and an optional name; converters such as <int:pk> capture parts of the URL and pass them to the view as keyword arguments. include() mounts another URL list under a prefix, and reverse() builds a URL from its name so links do not break when routes change.

Full answer

The root URL list is set by ROOT_URLCONF, normally project/urls.py. Django walks urlpatterns from top to bottom and stops at the first match.

path(route, view, name=None):

  • path("students/", views.student_list, name="student-list")
  • path("students/<int:pk>/", views.student_detail, name="student-detail")

Built-in converters: str (default, no slash), int, slug, uuid, path (allows slashes). <int:pk> both checks that the segment is digits and converts it to a Python int before calling the view. If the segment is not a number, the pattern simply does not match, and Django moves on, which usually ends in a 404. You can register custom converters with register_converter.

re_path() uses regular expressions for cases converters cannot express.

include("library.urls") lets each app own its URLs. With app_name = "library" in the app's urls.py, names become namespaced: library:book-detail.

reverse("student-detail", kwargs={"pk": 7}) returns /students/7/. In templates, {% url 'student-detail' pk=7 %} does the same. Use names everywhere instead of hard-coding paths, so changing a route updates every link.

Trailing slashes: with APPEND_SLASH = True (the default) and CommonMiddleware, a GET to /students redirects to /students/ if only the slashed version exists.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.http import HttpResponse
from django.urls import path, reverse, resolve, include

def student_list(request):
    return HttpResponse("all students")

def student_detail(request, pk):
    return HttpResponse(f"student {pk} ({type(pk).__name__})")

def book_detail(request, slug):
    return HttpResponse(f"book {slug}")

library_patterns = ([path("books/<slug:slug>/", book_detail, name="book-detail")], "library")

urlpatterns = [
    path("students/", student_list, name="student-list"),
    path("students/<int:pk>/", student_detail, name="student-detail"),
    path("library/", include(library_patterns)),
]

settings.ROOT_URLCONF = __name__

print(reverse("student-detail", kwargs={"pk": 7}))
print(reverse("library:book-detail", kwargs={"slug": "wings-of-fire"}))

match = resolve("/students/42/")
print(match.view_name, match.kwargs)
print(match.func(None, **match.kwargs).content.decode())

from django.urls import Resolver404
try:
    resolve("/students/abc/")
except Resolver404:
    print("/students/abc/ does not match any pattern")

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): /students/7/ /library/books/wings-of-fire/ student-detail {'pk': 42} student 42 (int) /students/abc/ does not match any pattern

Key points

  • urlpatterns are checked in order; first match wins
  • Converters validate and convert captured values
  • include() and app_name give each app its own namespaced URLs
  • reverse() and {% url %} build links from names
  • Non-matching converters lead to a 404, not a crash

Common mistakes

  • Hard-coding URLs in templates instead of using {% url %}
  • Placing a broad pattern above a specific one so the specific one never matches
  • Expecting <int:pk> to give a string
  • Forgetting app_name and then getting NoReverseMatch with a namespaced name

Follow-ups

  • How would you write a custom path converter for a year like 2026?
  • What causes NoReverseMatch and how do you debug it?
  • When would you still use re_path()?

Tips

  • Mention that order matters in urlpatterns
  • Explain that converters do both validation and type conversion
  • Recommend reverse() and named URLs as a maintenance habit