Episode 15 of 32

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?

ApproachExampleProblem
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 name parameter in path()
  • Use app_name for namespacing to avoid name conflicts
  • {% url 'namespace:name' %} resolves URLs in templates
  • reverse() resolves URLs in Python code (views)