urlresolvers.txt 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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`` is either the function name (either a function reference, or the
  11. string version of the name, if you used that form in ``urlpatterns``) or the
  12. :ref:`URL pattern name <naming-url-patterns>`. Normally, you won't need to
  13. worry about the ``urlconf`` parameter and will only pass in the positional and
  14. keyword arguments to use in the URL matching. For example::
  15. from django.core.urlresolvers import reverse
  16. def myview(request):
  17. return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
  18. The ``reverse()`` function can reverse a large variety of regular expression
  19. patterns for URLs, but not every possible one. The main restriction at the
  20. moment is that the pattern cannot contain alternative choices using the
  21. vertical bar (``"|"``) character. You can quite happily use such patterns for
  22. matching against incoming URLs and sending them off to views, but you cannot
  23. reverse such patterns.
  24. The ``current_app`` argument allows you to provide a hint to the resolver
  25. indicating the application to which the currently executing view belongs.
  26. This ``current_app`` argument is used as a hint to resolve application
  27. namespaces into URLs on specific application instances, according to the
  28. :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
  29. You can use ``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. .. admonition:: Make sure your views are all correct.
  34. As part of working out which URL names map to which patterns, the
  35. ``reverse()`` function has to import all of your URLconf files and examine
  36. the name of each view. This involves importing each view function. If
  37. there are *any* errors whilst importing any of your view functions, it
  38. will cause ``reverse()`` to raise an error, even if that view function is
  39. not the one you are trying to reverse.
  40. Make sure that any views you reference in your URLconf files exist and can
  41. be imported correctly. Do not include lines that reference views you
  42. haven't written yet, because those views will not be importable.
  43. .. note::
  44. The string returned by ``reverse()`` is already
  45. :ref:`urlquoted <uri-and-iri-handling>`. For example::
  46. >>> reverse('cities', args=[u'Orléans'])
  47. '.../Orl%C3%A9ans/'
  48. Applying further encoding (such as :meth:`~django.utils.http.urlquote` or
  49. ``urllib.quote``) to the output of ``reverse()`` may produce undesirable
  50. results.
  51. reverse_lazy()
  52. --------------
  53. .. versionadded:: 1.4
  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 an
  76. :class:`~django.http.Http404` exception.
  77. .. class:: ResolverMatch
  78. .. attribute:: ResolverMatch.func
  79. The view function that would be used to serve the URL
  80. .. attribute:: ResolverMatch.args
  81. The arguments that would be passed to the view function, as
  82. parsed from the URL.
  83. .. attribute:: ResolverMatch.kwargs
  84. The keyword arguments that would be passed to the view
  85. function, as parsed from the URL.
  86. .. attribute:: ResolverMatch.url_name
  87. The name of the URL pattern that matches the URL.
  88. .. attribute:: ResolverMatch.app_name
  89. The application namespace for the URL pattern that matches the
  90. URL.
  91. .. attribute:: ResolverMatch.namespace
  92. The instance namespace for the URL pattern that matches the
  93. URL.
  94. .. attribute:: ResolverMatch.namespaces
  95. The list of individual namespace components in the full
  96. instance namespace for the URL pattern that matches the URL.
  97. i.e., if the namespace is ``foo:bar``, then namespaces will be
  98. ``['foo', 'bar']``.
  99. A :class:`ResolverMatch` object can then be interrogated to provide
  100. information about the URL pattern that matches a URL::
  101. # Resolve a URL
  102. match = resolve('/some/path/')
  103. # Print the URL pattern that matches the URL
  104. print(match.url_name)
  105. A :class:`ResolverMatch` object can also be assigned to a triple::
  106. func, args, kwargs = resolve('/some/path/')
  107. One possible use of :func:`~django.core.urlresolvers.resolve` would be to test
  108. whether a view would raise a ``Http404`` error before redirecting to it::
  109. from urlparse import urlparse
  110. from django.core.urlresolvers import resolve
  111. from django.http import HttpResponseRedirect, Http404
  112. def myview(request):
  113. next = request.META.get('HTTP_REFERER', None) or '/'
  114. response = HttpResponseRedirect(next)
  115. # modify the request and response as required, e.g. change locale
  116. # and set corresponding locale cookie
  117. view, args, kwargs = resolve(urlparse(next)[2])
  118. kwargs['request'] = request
  119. try:
  120. view(*args, **kwargs)
  121. except Http404:
  122. return HttpResponseRedirect('/')
  123. return response
  124. get_script_prefix()
  125. -------------------
  126. .. function:: get_script_prefix()
  127. Normally, you should always use :func:`~django.core.urlresolvers.reverse` to
  128. define URLs within your application. However, if your application constructs
  129. part of the URL hierarchy itself, you may occasionally need to generate URLs.
  130. In that case, you need to be able to find the base URL of the Django project
  131. within its Web server (normally, :func:`~django.core.urlresolvers.reverse`
  132. takes care of this for you). In that case, you can call
  133. ``get_script_prefix()``, which will return the script prefix portion of the URL
  134. for your Django project. If your Django project is at the root of its web
  135. server, this is always ``"/"``.