urlresolvers.txt 7.3 KB

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