Named URL's
Reference URLs by name instead of hardcoding paths — use the url template tag and reverse() for maintainable, flexible routing.
Named URLs
Hardcoding URLs in templates is fragile — if you change a URL pattern, you have to update every link. Named URLs let you reference routes by name and Django resolves them automatically.
Naming URLs
# articles/urls.py
app_name = 'articles' # Namespace
urlpatterns = [
path('', views.article_list, name='list'),
path('<slug:slug>/', views.article_detail, name='detail'),
]
Using Named URLs in Templates
<!-- Instead of hardcoding: -->
<a href="/articles/">All Articles</a>
<!-- Use the url tag: -->
<a href="{% url 'articles:list' %}">All Articles</a>
<!-- With parameters: -->
<a href="{% url 'articles:detail' slug=article.slug %}">
{{ article.title }}
</a>
Using reverse() in Views
from django.urls import reverse
from django.shortcuts import redirect
def my_view(request):
url = reverse('articles:list')
return redirect(url)
# With parameters:
url = reverse('articles:detail', kwargs={'slug': 'my-post'})
Why Named URLs?
| Approach | Example | Problem |
|---|---|---|
| Hardcoded | /articles/my-post/ | Breaks if URL pattern changes |
| Named | {% url 'articles:detail' slug='my-post' %} | Always resolves to the correct URL |
Key Takeaways
- Name your URL patterns with the
nameparameter inpath() - Use
app_namefor namespacing to avoid name conflicts {% url 'namespace:name' %}resolves URLs in templatesreverse()resolves URLs in Python code (views)