0
0
Djangoframework~5 mins

Reverse URL resolution with reverse in Django

Choose your learning style9 modes available
Introduction

Reverse URL resolution helps you get the URL path by using the name of the URL pattern. This avoids hardcoding URLs and makes your code easier to maintain.

When you want to create links in your Django templates or views without typing the full URL.
When you change URL patterns but want your code to still work without updates.
When you want to redirect users to a named URL in your views.
When you want to generate URLs dynamically based on URL names and parameters.
Syntax
Django
from django.urls import reverse

url = reverse('url_name', args=[positional_args], kwargs={named_args})

reverse takes the URL pattern name as the first argument.

You can pass positional arguments with args or named arguments with kwargs to fill URL parameters.

Examples
Get the URL for the pattern named 'home' with no parameters.
Django
reverse('home')
Get the URL for 'article-detail' with a positional argument 42.
Django
reverse('article-detail', args=[42])
Get the URL for 'profile' using a named argument 'username' with value 'alice'.
Django
reverse('profile', kwargs={'username': 'alice'})
Sample Program

This example shows how to define URL patterns with names and use reverse to get their URLs in a view. It returns a response listing the URLs generated by reverse.

Django
from django.urls import path, reverse
from django.http import HttpResponse
from django.shortcuts import redirect

# Define URL patterns
urlpatterns = [
    path('', lambda request: HttpResponse('Home Page'), name='home'),
    path('article/<int:id>/', lambda request, id: HttpResponse(f'Article {id}'), name='article-detail'),
    path('user/<str:username>/', lambda request, username: HttpResponse(f'User {username}'), name='profile'),
]

# Example usage of reverse

def example_view(request):
    home_url = reverse('home')
    article_url = reverse('article-detail', args=[10])
    profile_url = reverse('profile', kwargs={'username': 'bob'})

    response_text = f"Home URL: {home_url}\nArticle URL: {article_url}\nProfile URL: {profile_url}"
    return HttpResponse(response_text)
OutputSuccess
Important Notes

Always use URL names in reverse to avoid breaking links if URLs change.

If your URL pattern requires parameters, you must provide them via args or kwargs.

Using reverse helps keep your Django app DRY (Don't Repeat Yourself).

Summary

Reverse URL resolution lets you get URLs by their name instead of hardcoding.

Use reverse with URL names and parameters to build URLs dynamically.

This makes your Django code easier to maintain and less error-prone.