In Django, URL routing is managed using the path() and re_path() functions, which map URLs to views. These functions are used in the urls.py files to define URL patterns for your project and app.
path() uses simple readable patternsre_path() uses regular expressionsThe path() function is used to define URL patterns that are simple and readable.
// Basic syntax of path() function
path('url_pattern/', view_function, name='url_name')
// Defining simple URL routes using path()
from django.urls import path
from . import views
urlpatterns = [
path('home/', views.home, name='home'),
path('about/', views.about, name='about'),
]
The re_path() function is used for complex URL patterns that require regular expressions.
// Basic syntax of re_path() with regex
re_path(r'url_pattern/', view_function, name='url_name')
// URL pattern capturing numeric ID using regex
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^post/(?P<id>\d+)/$', views.post_detail, name='post_detail'),
]
When a user visits /post/5/, Django extracts the number 5 and passes it as an argument to the post_detail view function.
Try changing the number in the URL (e.g. /post/10/) and observe how Django dynamically routes the request.
Matched Pattern: None
Extracted Data: N/A
Type a URL to see how it resolves.
path()re_path()path() for readabilityre_path() only when regex is required