urlresolvers.txt 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. =================================
  2. ``django.urls`` utility functions
  3. =================================
  4. .. module:: django.urls
  5. ``reverse()``
  6. =============
  7. The ``reverse()`` function can be used to return an absolute path reference
  8. for a given view and optional parameters, similar to the :ttag:`url` tag:
  9. .. function:: reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None, *, query=None, fragment=None)
  10. ``viewname`` can be a :ref:`URL pattern name <naming-url-patterns>` or the
  11. callable view object used in the URLconf. For example, given the following
  12. ``url``::
  13. from news import views
  14. path("archive/", views.archive, name="news-archive")
  15. you can use any of the following to reverse the URL::
  16. # using the named URL
  17. reverse("news-archive")
  18. # passing a callable object
  19. # (This is discouraged because you can't reverse namespaced views this way.)
  20. from news import views
  21. reverse(views.archive)
  22. If the URL accepts arguments, you may pass them in ``args``. For example::
  23. from django.urls import reverse
  24. def myview(request):
  25. return HttpResponseRedirect(reverse("arch-summary", args=[1945]))
  26. You can also pass ``kwargs`` instead of ``args``. For example:
  27. .. code-block:: pycon
  28. >>> reverse("admin:app_list", kwargs={"app_label": "auth"})
  29. '/admin/auth/'
  30. ``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.
  31. If no match can be made, ``reverse()`` raises a
  32. :class:`~django.urls.NoReverseMatch` exception.
  33. The ``reverse()`` function can reverse a large variety of regular expression
  34. patterns for URLs, but not every possible one. The main restriction at the
  35. moment is that the pattern cannot contain alternative choices using the
  36. vertical bar (``"|"``) character. You can quite happily use such patterns for
  37. matching against incoming URLs and sending them off to views, but you cannot
  38. reverse such patterns.
  39. The ``current_app`` argument allows you to provide a hint to the resolver
  40. indicating the application to which the currently executing view belongs.
  41. This ``current_app`` argument is used as a hint to resolve application
  42. namespaces into URLs on specific application instances, according to the
  43. :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
  44. The ``urlconf`` argument is the URLconf module containing the URL patterns to
  45. use for reversing. By default, the root URLconf for the current thread is used.
  46. The ``query`` keyword argument specifies parameters to be added to the returned
  47. URL. It can accept an instance of :class:`~django.http.QueryDict` (such as
  48. ``request.GET``) or any value compatible with :func:`urllib.parse.urlencode`.
  49. The encoded query string is appended to the resolved URL, prefixed by a ``?``.
  50. The ``fragment`` keyword argument specifies a fragment identifier to be
  51. appended to the returned URL (that is, after the path and query string,
  52. preceded by a ``#``).
  53. For example:
  54. .. code-block:: pycon
  55. >>> from django.urls import reverse
  56. >>> reverse("admin:index", query={"q": "biscuits", "page": 2}, fragment="results")
  57. '/admin/?q=biscuits&page=2#results'
  58. >>> reverse("admin:index", query=[("color", "blue"), ("color", 1), ("none", None)])
  59. '/admin/?color=blue&color=1&none=None'
  60. >>> reverse("admin:index", query={"has empty spaces": "also has empty spaces!"})
  61. '/admin/?has+empty+spaces=also+has+empty+spaces%21'
  62. >>> reverse("admin:index", fragment="no encoding is done")
  63. '/admin/#no encoding is done'
  64. .. versionchanged:: 5.2
  65. The ``query`` and ``fragment`` arguments were added.
  66. .. note::
  67. The string returned by ``reverse()`` is already
  68. :ref:`urlquoted <uri-and-iri-handling>`. For example:
  69. .. code-block:: pycon
  70. >>> reverse("cities", args=["Orléans"])
  71. '.../Orl%C3%A9ans/'
  72. Applying further encoding (such as :func:`urllib.parse.quote`) to the output
  73. of ``reverse()`` may produce undesirable results.
  74. .. admonition:: Reversing class-based views by view object
  75. The view object can also be the result of calling
  76. :meth:`~django.views.generic.base.View.as_view` if the same view object is
  77. used in the URLConf. Following the original example, the view object could
  78. be defined as:
  79. .. code-block:: python
  80. :caption: ``news/views.py``
  81. from django.views import View
  82. class ArchiveView(View): ...
  83. archive = ArchiveView.as_view()
  84. However, remember that namespaced views cannot be reversed by view object.
  85. ``reverse_lazy()``
  86. ==================
  87. A lazily evaluated version of `reverse()`_.
  88. .. function:: reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
  89. It is useful for when you need to use a URL reversal before your project's
  90. URLConf is loaded. Some common cases where this function is necessary are:
  91. * providing a reversed URL as the ``url`` attribute of a generic class-based
  92. view.
  93. * providing a reversed URL to a decorator (such as the ``login_url`` argument
  94. for the :func:`django.contrib.auth.decorators.permission_required`
  95. decorator).
  96. * providing a reversed URL as a default value for a parameter in a function's
  97. signature.
  98. ``resolve()``
  99. =============
  100. The ``resolve()`` function can be used for resolving URL paths to the
  101. corresponding view functions. It has the following signature:
  102. .. function:: resolve(path, urlconf=None)
  103. ``path`` is the URL path you want to resolve. As with
  104. :func:`~django.urls.reverse`, you don't need to worry about the ``urlconf``
  105. parameter. The function returns a :class:`ResolverMatch` object that allows you
  106. to access various metadata about the resolved URL.
  107. If the URL does not resolve, the function raises a
  108. :exc:`~django.urls.Resolver404` exception (a subclass of
  109. :class:`~django.http.Http404`) .
  110. .. class:: ResolverMatch
  111. .. attribute:: ResolverMatch.func
  112. The view function that would be used to serve the URL
  113. .. attribute:: ResolverMatch.args
  114. The arguments that would be passed to the view function, as
  115. parsed from the URL.
  116. .. attribute:: ResolverMatch.kwargs
  117. All keyword arguments that would be passed to the view function, i.e.
  118. :attr:`~ResolverMatch.captured_kwargs` and
  119. :attr:`~ResolverMatch.extra_kwargs`.
  120. .. attribute:: ResolverMatch.captured_kwargs
  121. The captured keyword arguments that would be passed to the view
  122. function, as parsed from the URL.
  123. .. attribute:: ResolverMatch.extra_kwargs
  124. The additional keyword arguments that would be passed to the view
  125. function.
  126. .. attribute:: ResolverMatch.url_name
  127. The name of the URL pattern that matches the URL.
  128. .. attribute:: ResolverMatch.route
  129. The route of the matching URL pattern.
  130. For example, if ``path('users/<id>/', ...)`` is the matching pattern,
  131. ``route`` will contain ``'users/<id>/'``.
  132. .. attribute:: ResolverMatch.tried
  133. The list of URL patterns tried before the URL either matched one or
  134. exhausted available patterns.
  135. .. attribute:: ResolverMatch.app_name
  136. The application namespace for the URL pattern that matches the
  137. URL.
  138. .. attribute:: ResolverMatch.app_names
  139. The list of individual namespace components in the full
  140. application namespace for the URL pattern that matches the URL.
  141. For example, if the ``app_name`` is ``'foo:bar'``, then ``app_names``
  142. will be ``['foo', 'bar']``.
  143. .. attribute:: ResolverMatch.namespace
  144. The instance namespace for the URL pattern that matches the
  145. URL.
  146. .. attribute:: ResolverMatch.namespaces
  147. The list of individual namespace components in the full
  148. instance namespace for the URL pattern that matches the URL.
  149. i.e., if the namespace is ``foo:bar``, then namespaces will be
  150. ``['foo', 'bar']``.
  151. .. attribute:: ResolverMatch.view_name
  152. The name of the view that matches the URL, including the namespace if
  153. there is one.
  154. A :class:`ResolverMatch` object can then be interrogated to provide
  155. information about the URL pattern that matches a URL::
  156. # Resolve a URL
  157. match = resolve("/some/path/")
  158. # Print the URL pattern that matches the URL
  159. print(match.url_name)
  160. A :class:`ResolverMatch` object can also be assigned to a triple::
  161. func, args, kwargs = resolve("/some/path/")
  162. One possible use of :func:`~django.urls.resolve` would be to test whether a
  163. view would raise a ``Http404`` error before redirecting to it::
  164. from urllib.parse import urlsplit
  165. from django.urls import resolve
  166. from django.http import Http404, HttpResponseRedirect
  167. def myview(request):
  168. next = request.META.get("HTTP_REFERER", None) or "/"
  169. response = HttpResponseRedirect(next)
  170. # modify the request and response as required, e.g. change locale
  171. # and set corresponding locale cookie
  172. view, args, kwargs = resolve(urlsplit(next).path)
  173. kwargs["request"] = request
  174. try:
  175. view(*args, **kwargs)
  176. except Http404:
  177. return HttpResponseRedirect("/")
  178. return response
  179. ``get_script_prefix()``
  180. =======================
  181. .. function:: get_script_prefix()
  182. Normally, you should always use :func:`~django.urls.reverse` to define URLs
  183. within your application. However, if your application constructs part of the
  184. URL hierarchy itself, you may occasionally need to generate URLs. In that
  185. case, you need to be able to find the base URL of the Django project within
  186. its web server (normally, :func:`~django.urls.reverse` takes care of this for
  187. you). In that case, you can call ``get_script_prefix()``, which will return
  188. the script prefix portion of the URL for your Django project. If your Django
  189. project is at the root of its web server, this is always ``"/"``.
  190. .. warning::
  191. This function **cannot** be used outside of the request-response cycle
  192. since it relies on values initialized during that cycle.