Django Path Converters
A path converter is a part of an address that catches a value. The value travels to the view as an argument.
Catch a year
This pattern catches a whole number as year.
path("post/<int:year>/", year_view)Catch a slug
This pattern catches a slug as slug.
path("page/<slug:slug>/", page_view)Ask for a year
The test client asks for the year 2026. The view prints the caught year.
print(client.get("/post/2026/").content.decode())Ask for a slug
The test client asks for a slug. The view prints the caught slug.
print(client.get("/page/django-intro/").content.decode())Example
import django
from django.conf import settings
settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()
from django.http import HttpResponse
from django.urls import path
def year_view(request, year):
return HttpResponse(f"Year: {year}")
def page_view(request, slug):
return HttpResponse(f"Slug: {slug}")
urlpatterns = [path("post/<int:year>/", year_view), path("page/<slug:slug>/", page_view)]
from django.test import Client
client = Client()
print(client.get("/post/2026/").content.decode())
print(client.get("/page/django-intro/").content.decode())Key points
- A converter sits inside angle brackets in a route string.
- The int converter catches whole numbers.
- The str converter catches text.
- The slug converter catches letters, numbers, hyphens, and underscores.
- The caught value arrives in the view as an argument.
In this example, the setup lines configure Django. The year view returns the caught year as text. The slug view returns the caught slug as text. The pattern list pairs each address with its view. The test client asks for both addresses and prints the pages.
Note
A converter keeps a bad address from reaching the view.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does <int:year> catch?