URL Routing in Django
basic · Django
The Traffic Controller Layer In Django’s Model-View-Template (MVT) architecture, the URL Routing Engine acts as the initial entry gatekeeper. When a browser dispatches an HTTP request, Django intercepts the network path string, cross-references it against a centralized routing registry, and maps it directly to the appropriate logic View function. By separating the visible URL string from the underlying Python code structure, Django ensures your web routing layouts remain semantic, highly flexible, and decoupled from your backend business components. Configuring URL Patterns URL patterns are registered inside a centralized list named urlpatterns within urls.py modules. Django evaluates these path patterns sequentially from top to bottom, stopping the moment it encounters the first match. To process these routes, Django provides two alternative parsing functions: path() for standard semantic strings and re_path() for complex structural matches using Regular Expressions. 1. Standard Route Mapping: path() The path() function handles clean, readable URL layouts. It supports a straightforward string match interface and offers special type-casting brackets to capture parameters from the URL natively. Python from django.urls import path from . import views urlpatterns = [ # Static pattern matching: Handles exactly 'http://domain.com/status/' path('status/', views.system_status_view), ] 2. Regex-Based Route Mapping: re_path() When standard path matching cannot support complex string criteria—such as enforcing exact alphanumeric patterns or matching historical slug structures—you use re_path() . It uses standard Python Regular Expression syntax to validate matching routes. Python from django.urls import re_path from . import views urlpatterns = [ # Matches /archive/2024/ or /archive/2026/, restricting the variable to exactly 4 digits re_path(r'^archive/(?P<year>[0-9]{4})/