urlresolvers.txt 8.0 KB

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