Django Path Converters Validate and Type URL Segments Before the View Runs

In progress Django

A Django URL pattern such as users/<int:user_id>/ does two jobs at once: it captures part of the path, and its converter decides whether the request matches at all and which Python type the view receives. A view behind <int:...> never sees "abc": the pattern doesn't match, Django tries the next one, and the request ends in a 404 if none fits.

How a Captured Segment Reaches the View

# urls.py
urlpatterns = [
    path("profile/<str:username>/", views.user_profile, name="user_profile"),
    path("users/<int:user_id>/", views.user_detail, name="user_detail"),
]

# views.py
def user_detail(request, user_id):  # already an int
    user = get_object_or_404(get_user_model(), pk=user_id)
    return render(request, "user_detail.html", {"user": user})

The name inside the angle brackets becomes a keyword argument of the view, so the view's parameter must have exactly that name. <username> without a converter means <str:username>.

The Built-in Converters

Converter Matches View receives
str (default) any non-empty text without / str
int zero or a positive integer int
slug ASCII letters, digits, hyphens and underscores str
uuid a lowercase UUID with dashes uuid.UUID
path any non-empty text, / included str

For other formats (a four-digit year, a hex ID), write a converter class with a regex, to_python() and to_url(), and register it with register_converter(). reverse() and {% url %} call to_url() to build links back.

re_path for Formats a Converter Can't Express

re_path() matches with a regular expression instead of converters. A named group becomes a keyword argument (always a string); an unnamed group is passed positionally:

re_path(r"^dashboard/users/(?P<user_id>[0-9]{4})/$", views.user_detail)

Here anything but exactly four digits gives a 404 before the view runs. A custom converter does the same more readably when the format is reused.

What a Converter Does Not Check

References

Review cards

Flashcard What happens when a path converter doesn't match a URL segment?

That URL pattern doesn't match, so Django tries the next pattern. If none matches, the request ends in a 404 and the view never runs.

Flashcard Why must the name in <int:user_id> match the view's parameter name?

Django calls the view with that name as a keyword argument. A different parameter name raises TypeError: unexpected keyword argument on every request.

Quiz Which converter matches a segment of letters, digits, hyphens and underscores, such as `my-first-post`?
  • str
  • slug
  • int
  • uuid

The slug converter matches ASCII letters, digits, hyphens, and underscores, making it suitable for URL segments containing these characters.

Flashcard What does <int:user_id> not guarantee, and how does the view cover it?

That the row exists or that the visitor may see it. Use get_object_or_404() so a missing ID gives a 404, and check ownership or permissions in the view.