1.re_path() and regex patterns
re_path() matches a URL with a regular expression instead of path()'s converter syntax — named groups ((?P<name>...)) capture values, but every captured value arrives as a plain string, unlike path()'s automatic int/slug/uuid conversion.
Key features
- Named groups use (?P<name>pattern) — django.urls.path() equivalents like <int:name> don't exist in regex syntax
- Every captured value is a plain str — re_path() has no equivalent of path()'s type converters
- Reach for re_path() only when path()'s five built-in converters (str, int, slug, uuid, path) can't express the pattern
- A regex mistake (wrong anchor, missing escape) just fails to match — no error, the request 404s or falls through to the next pattern
- path() is preferred by the docs for anything expressible with a converter — re_path() is the escape hatch, not the default
path() vs re_path() for the same route
Command
from django.urls import re_path
urlpatterns = [
re_path(r"^articles/(?P<year>[0-9]{4})/$", views.year_archive, name="year-archive"),
]re_path() matches with a regex and captures everything as a string — reach for it only when path()'s five converters genuinely can't express the pattern.