How does URL routing work in Django, and what is the difference between path() and re_path()?
Last updated
Django matches an incoming request's path against an ordered list of URL patterns in urlpatterns, and dispatches to the first view whose pattern matches. path() uses simple readable route syntax with typed converters, while re_path() uses regular expressions for more complex matching.
How routing works:
Django loads the root URLconf (
ROOT_URLCONF), checks patterns top to bottom, and stops at the first match.Captured parts of the URL are passed to the view as arguments;
include()lets you delegate to per-app URLconfs.
path()uses route converters:Syntax like
<int:id>captures and type-casts (int,str,slug,uuid,path).Cleaner and preferred for most routes.
re_path()uses regular expressions:Use named groups like
(?P<year>[0-9]{4})for complex patterns path converters can't express.More powerful but harder to read; reach for it only when needed.
[lang:python]
from django.urls import path, re_path
urlpatterns = [
path('articles/<int:year>/', views.year_archive),
re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
]