urlresolvers.txt 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 (in the
  9. :mod:`django.core.urlresolvers` module):
  10. .. function:: reverse(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
  11. ``viewname`` is either the function name (either a function reference, or the
  12. string version of the name, if you used that form in ``urlpatterns``) or the
  13. :ref:`URL pattern name <naming-url-patterns>`. Normally, you won't need to
  14. worry about the ``urlconf`` parameter and will only pass in the positional and
  15. keyword arguments to use in the URL matching. For example::
  16. from django.core.urlresolvers import reverse
  17. def myview(request):
  18. return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
  19. The ``reverse()`` function can reverse a large variety of regular expression
  20. patterns for URLs, but not every possible one. The main restriction at the
  21. moment is that the pattern cannot contain alternative choices using the
  22. vertical bar (``"|"``) character. You can quite happily use such patterns for
  23. matching against incoming URLs and sending them off to views, but you cannot
  24. reverse such patterns.
  25. The ``current_app`` argument allows you to provide a hint to the resolver
  26. indicating the application to which the currently executing view belongs.
  27. This ``current_app`` argument is used as a hint to resolve application
  28. namespaces into URLs on specific application instances, according to the
  29. :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
  30. You can use ``kwargs`` instead of ``args``. For example::
  31. >>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
  32. '/admin/auth/'
  33. ``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.
  34. .. admonition:: Make sure your views are all correct.
  35. As part of working out which URL names map to which patterns, the
  36. ``reverse()`` function has to import all of your URLconf files and examine
  37. the name of each view. This involves importing each view function. If
  38. there are *any* errors whilst importing any of your view functions, it
  39. will cause ``reverse()`` to raise an error, even if that view function is
  40. not the one you are trying to reverse.
  41. Make sure that any views you reference in your URLconf files exist and can
  42. be imported correctly. Do not include lines that reference views you
  43. haven't written yet, because those views will not be importable.
  44. .. note::
  45. The string returned by :meth:`~django.core.urlresolvers.reverse` is already
  46. :ref:`urlquoted <uri-and-iri-handling>`. For example::
  47. >>> reverse('cities', args=[u'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 :meth:`~django.core.urlresolvers.reverse`
  51. may produce undesirable results.
  52. reverse_lazy()
  53. --------------
  54. .. versionadded:: 1.4
  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 :func:`django.core.urlresolvers.resolve` function can be used for
  69. resolving URL paths to the corresponding view functions. It has the
  70. following signature:
  71. .. function:: resolve(path, urlconf=None)
  72. ``path`` is the URL path you want to resolve. As with
  73. :func:`~django.core.urlresolvers.reverse`, you don't need to
  74. worry about the ``urlconf`` parameter. The function returns a
  75. :class:`ResolverMatch` object that allows you
  76. to access various meta-data about the resolved URL.
  77. If the URL does not resolve, the function raises an
  78. :class:`~django.http.Http404` exception.
  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. A :class:`ResolverMatch` object can then be interrogated to provide
  102. information about the URL pattern that matches a URL::
  103. # Resolve a URL
  104. match = resolve('/some/path/')
  105. # Print the URL pattern that matches the URL
  106. print(match.url_name)
  107. A :class:`ResolverMatch` object can also be assigned to a triple::
  108. func, args, kwargs = resolve('/some/path/')
  109. One possible use of :func:`~django.core.urlresolvers.resolve` would be to test
  110. whether a view would raise a ``Http404`` error before redirecting to it::
  111. from urlparse import urlparse
  112. from django.core.urlresolvers import resolve
  113. from django.http import HttpResponseRedirect, Http404
  114. def myview(request):
  115. next = request.META.get('HTTP_REFERER', None) or '/'
  116. response = HttpResponseRedirect(next)
  117. # modify the request and response as required, e.g. change locale
  118. # and set corresponding locale cookie
  119. view, args, kwargs = resolve(urlparse(next)[2])
  120. kwargs['request'] = request
  121. try:
  122. view(*args, **kwargs)
  123. except Http404:
  124. return HttpResponseRedirect('/')
  125. return response
  126. permalink()
  127. -----------
  128. The :func:`django.db.models.permalink` decorator is useful for writing short
  129. methods that return a full URL path. For example, a model's
  130. ``get_absolute_url()`` method. See :func:`django.db.models.permalink` for more.
  131. get_script_prefix()
  132. -------------------
  133. .. function:: get_script_prefix()
  134. Normally, you should always use :func:`~django.core.urlresolvers.reverse` or
  135. :func:`~django.db.models.permalink` to define URLs within your application.
  136. However, if your application constructs part of the URL hierarchy itself, you
  137. may occasionally need to generate URLs. In that case, you need to be able to
  138. find the base URL of the Django project within its Web server
  139. (normally, :func:`~django.core.urlresolvers.reverse` takes care of this for
  140. you). In that case, you can call ``get_script_prefix()``, which will return the
  141. script prefix portion of the URL for your Django project. If your Django
  142. project is at the root of its Web server, this is always ``"/"``.