Path Converters
Part of the Django Basics section of Coddy's Django journey. Lesson 6 of 23.
Every table in the café has a QR code, and each code needs its own page. One route can match them all when part of it is a path converter. A calendar might use two:
path("calendar/<int:year>/<int:month>/", views.calendar),The part in angle brackets is a converter: a type, a colon, a name. int matches a whole number and turns it into a Python int. The view gets each value as an argument with that name:
def calendar(request, year, month):
return HttpResponse(f"<h2>{month} / {year}</h2>")For /calendar/2026/3/, Django calls calendar(request, year=2026, month=3). An address the converter does not match, like /calendar/next/3/, gets a 404 Page not found, and the view never runs.
Challenge
EasyGive every table its own page.
- In
menu/urls.py, add one route that matches/table/5/,/table/12/and any other whole number. Point it toviews.table. - In
menu/views.py, write a viewtable. Its second parameter has the converter's name. It returns<h1>Table 5</h1>for table 5.
Open /table/12/: you see Table 12.
Try it yourself
from django.urls import path
from . import views
urlpatterns = [
path("", views.home),
path("about/", views.about),
path("hours/", views.hours),
path("contact/", views.contact),
]
All lessons in Django Basics
Practice on your own: Django playground