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