Defining Named Routes
Assign unique identifiers to you're path configurations in the urls.py module using the name argument.
urlpatterns = [
path('auth/signin/', account_login, name='user_signin'),
]
Using Reverse Lookup in Views
Import the reverse function from django.urls. Call it with the route idantifier to generate the corresponding absolute path.
from django.urls import reverse
from django.shortcuts import redirect
def login_process(request):
target_path = reverse('user_signin')
return redirect(target_path)
Embedding Links in Templates
Use the {% url %} template tag within HTML files to resolve URLs dynamically during rendering.
<form action="{% url 'user_signin' %}" method="post">
Handling Parameterized Routes (Positional)
When utilizing regular expressions for unmatched capture groups, you must pass arguments positionally to the resolver.
Configuration:
re_path(r'^item/([0-9]+)/$', display_item, name='product_view')
View Logic:
Suppply an iterable containing the parameter values via the args key.
return redirect(reverse('product_view', args=(4502,)))
Template Usage: Arguments follow the order of definitions in the pattern.
<a href="{% url 'product_view' 4502 %}">Item Details</a>
Handling Parameterized Routes (Named Groups)
Capture groups defined by name allow for explicit keyword mapping, improving code readability and reducing errors regarding parameter order.
Configuration:
re_path(r'^stats/(?P<year>[0-9]{4})/$', statistics_view, name='annual_report')
View Logic: Pass a dictionary where keys match the regex group names.
return redirect(reverse('annual_report', kwargs={'year': 2023}))
Template Usage: Utilize keyword syntax when specifying parameters in the template tag.
<a href="{% url 'annual_report' year=2023 %}">Report Data</a>
Integrated Example
Below is a cohesive example demonstrating how data flows through routing, logic, and templates.
url_routing.py
from django.conf.urls import url
from app.views import dashboard_handler
urlpatterns = [
url(r'^dashboard/(\d+)/$', dashboard_handler, name='dash_view'),
]
views_logic.py
from django.shortcuts import render
def dashboard_handler(request, user_id):
# Construct URL programmatically
resolved_path = reverse('dash_view', args=(user_id,))
context_data = {
'path_info': resolved_path,
'id_value': user_id
}
return render(request, 'main_dashboard.html', context_data)
templates/main_dashboard.html
<!DOCTYPE html>
<html lang="en">
<head><title>Dashboard</title></head>
<body>
<h1>User ID: {{ id_value }}</h1>
<p>Resolved Link: {{ path_info }}</p>
<a href="{% url 'dash_view' pk=id_value %}">Refresh View</a>
</body>
</html>