urlresolvers.txt 7.3 KB

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