From 626c15dba0662d5b9f61cc7eddf985e514293d6f Mon Sep 17 00:00:00 2001 From: Duane Hilton Date: Mon, 22 Dec 2025 22:59:43 -0700 Subject: [PATCH] Fixed #30515 -- Documented resolve_url() in docs/topics/http/shortcuts.txt. --- docs/topics/http/shortcuts.txt | 72 ++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/docs/topics/http/shortcuts.txt b/docs/topics/http/shortcuts.txt index 300cf2041c..b5ab1888cb 100644 --- a/docs/topics/http/shortcuts.txt +++ b/docs/topics/http/shortcuts.txt @@ -184,6 +184,78 @@ original HTTP method:: return redirect(obj, preserve_request=True) # ... +``resolve_url()`` +================= + +.. function:: resolve_url(to, *args, **kwargs) + + Returns a URL string by resolving and normalizing the given ``to`` argument + into a concrete URL. The parameter ``to`` may be: + + * An object implementing :meth:`~django.db.models.Model.get_absolute_url`, + in which case the method will be called and its result returned. + + * A view name, view function, or view class, possibly with arguments passed + as ``*args`` and ``**kwargs``, in which case :func:`~django.urls.reverse` + will be used to reverse-resolve the view. + + * A URL string, which will be returned unchanged. + + This function is used internally by the :func:`redirect` shortcut to + determine the target URL for the redirect location. + +Examples +-------- + +#. Resolving a URL for a model that defines + :meth:`~django.db.models.Model.get_absolute_url`: + + .. code-block:: python + :caption: ``models.py`` + + from django.db import models + from django.urls import reverse + + + class Article(models.Model): + title = models.CharField(max_length=100) + + def get_absolute_url(self): + return reverse("article-detail", args=[self.pk]) + + + .. code-block:: python + :caption: ``views.py`` + + from django.http import JsonResponse + from django.shortcuts import get_object_or_404, resolve_url + from .models import Article + + + def article_api_view(request, pk): + """Return metadata about an article, including its canonical URL.""" + article = get_object_or_404(Article, pk=pk) + return JsonResponse( + { + "id": article.pk, + "title": article.title, + "url": resolve_url(article), + } + ) + +#. Resolving a target URL for use outside of a redirect, such as in an HTTP + response header:: + + from django.conf import settings + from django.http import HttpResponse + from django.shortcuts import resolve_url + + + def login_success(request): + response = HttpResponse("Login successful") + response["X-Next-URL"] = resolve_url(settings.LOGIN_REDIRECT_URL) + return response + ``get_object_or_404()`` =======================