diff options
| author | Duane Hilton <duane9@gmail.com> | 2025-12-22 22:59:43 -0700 |
|---|---|---|
| committer | Natalia <124304+nessita@users.noreply.github.com> | 2025-12-26 12:30:34 -0300 |
| commit | 90daa655486c7fc69e9dad41c5e96f00339a3b9b (patch) | |
| tree | 7e8ec796cefd02f5e749c51e5ba3b09f004e1ee9 /docs | |
| parent | d35daf8600a66c0ff20e36f82969df61a7fc4981 (diff) | |
[6.0.x] Fixed #30515 -- Documented resolve_url() in docs/topics/http/shortcuts.txt.
Backport of 626c15dba0662d5b9f61cc7eddf985e514293d6f from main.
Diffstat (limited to 'docs')
| -rw-r--r-- | docs/topics/http/shortcuts.txt | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/docs/topics/http/shortcuts.txt b/docs/topics/http/shortcuts.txt index e5da762d78..9d3078c4f7 100644 --- a/docs/topics/http/shortcuts.txt +++ b/docs/topics/http/shortcuts.txt @@ -188,6 +188,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()`` ======================= |
