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.
Reverse URL resolution with reverse in 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.
reverse('home')reverse('article-detail', args=[42])
reverse('profile', kwargs={'username': 'alice'})
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.
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)
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).
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.