0
0
Djangoframework~5 mins

Named URLs for maintainability in Django

Choose your learning style9 modes available
Introduction

Named URLs help you change web addresses easily without breaking links. They make your code cleaner and easier to update.

When you want to link to a page in templates or views without hardcoding the URL.
When you plan to change URL patterns later but want to keep links working.
When you want to avoid mistakes by using a single source of truth for URLs.
When you build large projects with many pages and links.
When you want to improve readability and maintainability of your code.
Syntax
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.

Examples
Defines a URL named 'home' for the home page.
Django
path('home/', views.home, name='home')
Defines a URL with a dynamic integer parameter and names it 'article-detail'.
Django
path('article/<int:id>/', views.article_detail, name='article-detail')
In a template, this generates the URL for the named URL 'home'.
Django
{% url 'home' %}
In a view, this redirects to the URL named 'article-detail' with id 5.
Django
redirect('article-detail', id=5)
Sample Program

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.

Django
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')
]
OutputSuccess
Important Notes

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.

Summary

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().