Capturing URL Parameters with Path Converters
To extract typed variables from URL segments, use path converters in your URL patterns. Converters allow you to capture parts of the URL and pass them as specific Python types to your view functions.
Capturing Typed Parameters
Use the syntax <converter:name> within the path() function to capture a URL segment. The captured value is passed to the view as a keyword argument.
from django.urls import path
from . import views
urlpatterns = [
# Captures an integer and passes it as 'year'
path("articles/<int:year>/", views.year_archive),
# Captures a slug (letters, numbers, hyphens, underscores)
path("articles/<slug:title>/", views.article_detail),
# Captures a UUID object
path("user/<uuid:user_id>/", views.user_profile),
]
Built-in Converters
The following converters are available by default in django.urls.converters:
str: Matches any non-empty string, excluding the path separator/. This is the default if a converter isn't specified. (Implemented byStringConverter)int: Matches one or more digits and returns anint. (Implemented byIntConverter)slug: Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. (Implemented bySlugConverter)uuid: Matches a formatted UUID. To prevent multiple URLs from mapping to the same page, dashes must be included and letters must be lowercase (e.g.,0751ad43-1339-4407-b4c1-246e039621f3). Returns auuid.UUIDinstance. (Implemented byUUIDConverter)path: Matches any non-empty string, including the path separator/. This allows you to match against a complete URL path rather than just a segment. (Implemented byPathConverter)
Using the Path Converter for Catch-all Routing
The path converter is useful for capturing file paths or nested structures. For example, django.contrib.flatpages uses it to match arbitrary page URLs:
# django/contrib/flatpages/urls.py
from django.urls import path
from django.contrib.flatpages import views
urlpatterns = [
path("<path:url>", views.flatpage, name="django.contrib.flatpages.views.flatpage"),
]
Creating Custom Converters
For more complex matching or custom Python types, you can create your own converter class. A converter must include:
- A
regexclass attribute. - A
to_python(self, value)method to convert the matched string into the type passed to the view. - A
to_url(self, value)method to convert the Python type back into a string for URL reversing.
The following example from tests/urlpatterns/converters.py shows a converter for Base64 encoded data:
import base64
class Base64Converter:
regex = r"[a-zA-Z0-9+/]*={0,2}"
def to_python(self, value):
# Return the decoded bytes
return base64.b64decode(value, validate=True)
def to_url(self, value):
# Convert bytes back to a base64 string for reversing
return base64.b64encode(value).decode("ascii")
Registering Custom Converters
To use a custom converter in path(), you must register it using register_converter from django.urls.
from django.urls import path, register_converter
from . import converters, views
# Register the converter with a name to use in path()
register_converter(converters.Base64Converter, "base64")
urlpatterns = [
path("base64/<base64:value>/", views.decode_view, name="base64-detail"),
]
Troubleshooting and Error Handling
- Handling Non-Matches: If the
to_python()method of a converter raises aValueError, the URL resolver treats it as a non-match and continues checking other patterns. If no patterns match, a 404 is returned. Other exceptions raised into_python()will propagate and likely result in a 500 error. - Registration Conflicts: You cannot register a converter with a name that is already in use (e.g., trying to re-register "int"). Doing so will raise a
ValueError. - Parameter Naming: The name used in
<converter:name>must be a valid Python identifier. Avoid using names that conflict with Python keywords or built-in functions.