urlresolvers.txt 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 string containing the Python path to the view object, a
  11. :ref:`URL pattern name <naming-url-patterns>`, or the callable view object.
  12. For example, given the following ``url``::
  13. url(r'^archive/$', 'news.views.archive', name='news_archive')
  14. you can use any of the following to reverse the URL::
  15. # using the Python path
  16. reverse('news.views.archive')
  17. # using the named URL
  18. reverse('news_archive')
  19. # passing a callable object
  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.core.urlresolvers 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. >>> 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.core.urlresolvers.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. .. admonition:: Make sure your views are all correct.
  46. As part of working out which URL names map to which patterns, the
  47. ``reverse()`` function has to import all of your URLconf files and examine
  48. the name of each view. This involves importing each view function. If
  49. there are *any* errors whilst importing any of your view functions, it
  50. will cause ``reverse()`` to raise an error, even if that view function is
  51. not the one you are trying to reverse.
  52. Make sure that any views you reference in your URLconf files exist and can
  53. be imported correctly. Do not include lines that reference views you
  54. haven't written yet, because those views will not be importable.
  55. .. note::
  56. The string returned by ``reverse()`` is already
  57. :ref:`urlquoted <uri-and-iri-handling>`. For example::
  58. >>> reverse('cities', args=['Orléans'])
  59. '.../Orl%C3%A9ans/'
  60. Applying further encoding (such as :meth:`~django.utils.http.urlquote` or
  61. ``urllib.quote``) to the output of ``reverse()`` may produce undesirable
  62. results.
  63. reverse_lazy()
  64. --------------
  65. A lazily evaluated version of `reverse()`_.
  66. .. function:: reverse_lazy(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
  67. It is useful for when you need to use a URL reversal before your project's
  68. URLConf is loaded. Some common cases where this function is necessary are:
  69. * providing a reversed URL as the ``url`` attribute of a generic class-based
  70. view.
  71. * providing a reversed URL to a decorator (such as the ``login_url`` argument
  72. for the :func:`django.contrib.auth.decorators.permission_required`
  73. decorator).
  74. * providing a reversed URL as a default value for a parameter in a function's
  75. signature.
  76. resolve()
  77. ---------
  78. The ``resolve()`` function can be used for resolving URL paths to the
  79. corresponding view functions. It has the following signature:
  80. .. function:: resolve(path, urlconf=None)
  81. ``path`` is the URL path you want to resolve. As with
  82. :func:`~django.core.urlresolvers.reverse`, you don't need to
  83. worry about the ``urlconf`` parameter. The function returns a
  84. :class:`ResolverMatch` object that allows you
  85. to access various meta-data about the resolved URL.
  86. If the URL does not resolve, the function raises a
  87. :exc:`~django.core.urlresolvers.Resolver404` exception (a subclass of
  88. :class:`~django.http.Http404`) .
  89. .. class:: ResolverMatch
  90. .. attribute:: ResolverMatch.func
  91. The view function that would be used to serve the URL
  92. .. attribute:: ResolverMatch.args
  93. The arguments that would be passed to the view function, as
  94. parsed from the URL.
  95. .. attribute:: ResolverMatch.kwargs
  96. The keyword arguments that would be passed to the view
  97. function, as parsed from the URL.
  98. .. attribute:: ResolverMatch.url_name
  99. The name of the URL pattern that matches the URL.
  100. .. attribute:: ResolverMatch.app_name
  101. The application namespace for the URL pattern that matches the
  102. URL.
  103. .. attribute:: ResolverMatch.namespace
  104. The instance namespace for the URL pattern that matches the
  105. URL.
  106. .. attribute:: ResolverMatch.namespaces
  107. The list of individual namespace components in the full
  108. instance namespace for the URL pattern that matches the URL.
  109. i.e., if the namespace is ``foo:bar``, then namespaces will be
  110. ``['foo', 'bar']``.
  111. .. attribute:: ResolverMatch.view_name
  112. The name of the view that matches the URL, including the namespace if
  113. there is one.
  114. A :class:`ResolverMatch` object can then be interrogated to provide
  115. information about the URL pattern that matches a URL::
  116. # Resolve a URL
  117. match = resolve('/some/path/')
  118. # Print the URL pattern that matches the URL
  119. print(match.url_name)
  120. A :class:`ResolverMatch` object can also be assigned to a triple::
  121. func, args, kwargs = resolve('/some/path/')
  122. One possible use of :func:`~django.core.urlresolvers.resolve` would be to test
  123. whether a view would raise a ``Http404`` error before redirecting to it::
  124. from django.core.urlresolvers import resolve
  125. from django.http import HttpResponseRedirect, Http404
  126. from django.utils.six.moves.urllib.parse import urlparse
  127. def myview(request):
  128. next = request.META.get('HTTP_REFERER', None) or '/'
  129. response = HttpResponseRedirect(next)
  130. # modify the request and response as required, e.g. change locale
  131. # and set corresponding locale cookie
  132. view, args, kwargs = resolve(urlparse(next)[2])
  133. kwargs['request'] = request
  134. try:
  135. view(*args, **kwargs)
  136. except Http404:
  137. return HttpResponseRedirect('/')
  138. return response
  139. get_script_prefix()
  140. -------------------
  141. .. function:: get_script_prefix()
  142. Normally, you should always use :func:`~django.core.urlresolvers.reverse` to
  143. define URLs within your application. However, if your application constructs
  144. part of the URL hierarchy itself, you may occasionally need to generate URLs.
  145. In that case, you need to be able to find the base URL of the Django project
  146. within its Web server (normally, :func:`~django.core.urlresolvers.reverse`
  147. takes care of this for you). In that case, you can call
  148. ``get_script_prefix()``, which will return the script prefix portion of the URL
  149. for your Django project. If your Django project is at the root of its web
  150. server, this is always ``"/"``.