Named URLs help you change web addresses easily without breaking links. They make your code cleaner and easier to update.
Named URLs for maintainability in Django
path('page/', views.page_view, name='page_name')
The name parameter assigns a unique name to the URL pattern.
You use this name in templates and views to refer to the URL.
path('home/', views.home, name='home')
path('article/<int:id>/', views.article_detail, name='article-detail')
{% url 'home' %}redirect('article-detail', id=5)
This Django setup defines three URLs with names. The 'go_to_article' view redirects to the article detail page using the named URL and passes the article id. This shows how named URLs help keep links consistent and easy to update.
from django.urls import path from django.http import HttpResponse from django.shortcuts import redirect # Views def home(request): return HttpResponse('Welcome to Home Page') def article_detail(request, id): return HttpResponse(f'Article ID: {id}') def go_to_article(request): # Redirect to article with id 10 using named URL return redirect('article-detail', id=10) # URL patterns urlpatterns = [ path('home/', home, name='home'), path('article/<int:id>/', article_detail, name='article-detail'), path('go/', go_to_article, name='go-to-article') ]
Always use named URLs in templates and views instead of hardcoding paths.
If you change the URL pattern, you only update it in one place, the URLconf.
Use descriptive names that clearly identify the page or action.
Named URLs make your Django project easier to maintain and update.
Use the name parameter in path() to assign names.
Refer to URLs by name in templates with {% url %} and in views with functions like redirect().