2
0

urlresolvers.txt 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. =================================
  2. ``django.urls`` utility functions
  3. =================================
  4. .. module:: django.urls
  5. ``reverse()``
  6. =============
  7. If you need to use something similar to the :ttag:`url` template tag in
  8. your code, Django provides the following function:
  9. .. function:: reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=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. .. note::
  47. The string returned by ``reverse()`` is already
  48. :ref:`urlquoted <uri-and-iri-handling>`. For example:
  49. .. code-block:: pycon
  50. >>> reverse("cities", args=["Orléans"])
  51. '.../Orl%C3%A9ans/'
  52. Applying further encoding (such as :func:`urllib.parse.quote`) to the output
  53. of ``reverse()`` may produce undesirable results.
  54. .. admonition:: Reversing class-based views by view object
  55. The view object can also be the result of calling
  56. :meth:`~django.views.generic.base.View.as_view` if the same view object is
  57. used in the URLConf. Following the original example, the view object could
  58. be defined as:
  59. .. code-block:: python
  60. :caption: ``news/views.py``
  61. from django.views import View
  62. class ArchiveView(View): ...
  63. archive = ArchiveView.as_view()
  64. However, remember that namespaced views cannot be reversed by view object.
  65. ``reverse_lazy()``
  66. ==================
  67. A lazily evaluated version of `reverse()`_.
  68. .. function:: reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
  69. It is useful for when you need to use a URL reversal before your project's
  70. URLConf is loaded. Some common cases where this function is necessary are:
  71. * providing a reversed URL as the ``url`` attribute of a generic class-based
  72. view.
  73. * providing a reversed URL to a decorator (such as the ``login_url`` argument
  74. for the :func:`django.contrib.auth.decorators.permission_required`
  75. decorator).
  76. * providing a reversed URL as a default value for a parameter in a function's
  77. signature.
  78. ``resolve()``
  79. =============
  80. The ``resolve()`` function can be used for resolving URL paths to the
  81. corresponding view functions. It has the following signature:
  82. .. function:: resolve(path, urlconf=None)
  83. ``path`` is the URL path you want to resolve. As with
  84. :func:`~django.urls.reverse`, you don't need to worry about the ``urlconf``
  85. parameter. The function returns a :class:`ResolverMatch` object that allows you
  86. to access various metadata about the resolved URL.
  87. If the URL does not resolve, the function raises a
  88. :exc:`~django.urls.Resolver404` exception (a subclass of
  89. :class:`~django.http.Http404`) .
  90. .. class:: ResolverMatch
  91. .. attribute:: ResolverMatch.func
  92. The view function that would be used to serve the URL
  93. .. attribute:: ResolverMatch.args
  94. The arguments that would be passed to the view function, as
  95. parsed from the URL.
  96. .. attribute:: ResolverMatch.kwargs
  97. All keyword arguments that would be passed to the view function, i.e.
  98. :attr:`~ResolverMatch.captured_kwargs` and
  99. :attr:`~ResolverMatch.extra_kwargs`.
  100. .. attribute:: ResolverMatch.captured_kwargs
  101. The captured keyword arguments that would be passed to the view
  102. function, as parsed from the URL.
  103. .. attribute:: ResolverMatch.extra_kwargs
  104. The additional keyword arguments that would be passed to the view
  105. function.
  106. .. attribute:: ResolverMatch.url_name
  107. The name of the URL pattern that matches the URL.
  108. .. attribute:: ResolverMatch.route
  109. The route of the matching URL pattern.
  110. For example, if ``path('users/<id>/', ...)`` is the matching pattern,
  111. ``route`` will contain ``'users/<id>/'``.
  112. .. attribute:: ResolverMatch.tried
  113. The list of URL patterns tried before the URL either matched one or
  114. exhausted available patterns.
  115. .. attribute:: ResolverMatch.app_name
  116. The application namespace for the URL pattern that matches the
  117. URL.
  118. .. attribute:: ResolverMatch.app_names
  119. The list of individual namespace components in the full
  120. application namespace for the URL pattern that matches the URL.
  121. For example, if the ``app_name`` is ``'foo:bar'``, then ``app_names``
  122. will be ``['foo', 'bar']``.
  123. .. attribute:: ResolverMatch.namespace
  124. The instance namespace for the URL pattern that matches the
  125. URL.
  126. .. attribute:: ResolverMatch.namespaces
  127. The list of individual namespace components in the full
  128. instance namespace for the URL pattern that matches the URL.
  129. i.e., if the namespace is ``foo:bar``, then namespaces will be
  130. ``['foo', 'bar']``.
  131. .. attribute:: ResolverMatch.view_name
  132. The name of the view that matches the URL, including the namespace if
  133. there is one.
  134. A :class:`ResolverMatch` object can then be interrogated to provide
  135. information about the URL pattern that matches a URL::
  136. # Resolve a URL
  137. match = resolve("/some/path/")
  138. # Print the URL pattern that matches the URL
  139. print(match.url_name)
  140. A :class:`ResolverMatch` object can also be assigned to a triple::
  141. func, args, kwargs = resolve("/some/path/")
  142. One possible use of :func:`~django.urls.resolve` would be to test whether a
  143. view would raise a ``Http404`` error before redirecting to it::
  144. from urllib.parse import urlsplit
  145. from django.urls import resolve
  146. from django.http import Http404, HttpResponseRedirect
  147. def myview(request):
  148. next = request.META.get("HTTP_REFERER", None) or "/"
  149. response = HttpResponseRedirect(next)
  150. # modify the request and response as required, e.g. change locale
  151. # and set corresponding locale cookie
  152. view, args, kwargs = resolve(urlsplit(next).path)
  153. kwargs["request"] = request
  154. try:
  155. view(*args, **kwargs)
  156. except Http404:
  157. return HttpResponseRedirect("/")
  158. return response
  159. ``get_script_prefix()``
  160. =======================
  161. .. function:: get_script_prefix()
  162. Normally, you should always use :func:`~django.urls.reverse` to define URLs
  163. within your application. However, if your application constructs part of the
  164. URL hierarchy itself, you may occasionally need to generate URLs. In that
  165. case, you need to be able to find the base URL of the Django project within
  166. its web server (normally, :func:`~django.urls.reverse` takes care of this for
  167. you). In that case, you can call ``get_script_prefix()``, which will return
  168. the script prefix portion of the URL for your Django project. If your Django
  169. project is at the root of its web server, this is always ``"/"``.
  170. .. warning::
  171. This function **cannot** be used outside of the request-response cycle
  172. since it relies on values initialized during that cycle.