urlresolvers.txt 7.3 KB

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