Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/docs/ref/urlresolvers.txt
blob: 116aa4fcd0a38bb05d81a7976fe0fd06c9fb71e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
==============================================
``django.core.urlresolvers`` utility functions
==============================================

.. module:: django.core.urlresolvers

reverse()
---------

If you need to use something similar to the :ttag:`url` template tag in
your code, Django provides the following function:

.. function:: reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

``viewname`` can be a :ref:`URL pattern name <naming-url-patterns>` or the
callable view object. For example, given the following ``url``::

    from news import views

    url(r'^archive/$', views.archive, name='news_archive')

you can use any of the following to reverse the URL::

    # using the named URL
    reverse('news_archive')

    # passing a callable object
    # (This is discouraged because you can't reverse namespaced views this way.)
    from news import views
    reverse(views.archive)

If the URL accepts arguments, you may pass them in ``args``. For example::

    from django.core.urlresolvers import reverse

    def myview(request):
        return HttpResponseRedirect(reverse('arch-summary', args=[1945]))

You can also pass ``kwargs`` instead of ``args``. For example::

    >>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
    '/admin/auth/'

``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.

If no match can be made, ``reverse()`` raises a
:class:`~django.core.urlresolvers.NoReverseMatch` exception.

The ``reverse()`` function can reverse a large variety of regular expression
patterns for URLs, but not every possible one. The main restriction at the
moment is that the pattern cannot contain alternative choices using the
vertical bar (``"|"``) character. You can quite happily use such patterns for
matching against incoming URLs and sending them off to views, but you cannot
reverse such patterns.

The ``current_app`` argument allows you to provide a hint to the resolver
indicating the application to which the currently executing view belongs.
This ``current_app`` argument is used as a hint to resolve application
namespaces into URLs on specific application instances, according to the
:ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.

The ``urlconf`` argument is the URLconf module containing the url patterns to
use for reversing. By default, the root URLconf for the current thread is used.

.. note::

    The string returned by ``reverse()`` is already
    :ref:`urlquoted <uri-and-iri-handling>`. For example::

        >>> reverse('cities', args=['Orléans'])
        '.../Orl%C3%A9ans/'

    Applying further encoding (such as :meth:`~django.utils.http.urlquote` or
    ``urllib.quote``) to the output of ``reverse()`` may produce undesirable
    results.

reverse_lazy()
--------------

A lazily evaluated version of `reverse()`_.

.. function:: reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

It is useful for when you need to use a URL reversal before your project's
URLConf is loaded. Some common cases where this function is necessary are:

* providing a reversed URL as the ``url`` attribute of a generic class-based
  view.

* providing a reversed URL to a decorator (such as the ``login_url`` argument
  for the :func:`django.contrib.auth.decorators.permission_required`
  decorator).

* providing a reversed URL as a default value for a parameter in a function's
  signature.

resolve()
---------

The ``resolve()`` function can be used for resolving URL paths to the
corresponding view functions. It has the following signature:

.. function:: resolve(path, urlconf=None)

``path`` is the URL path you want to resolve. As with
:func:`~django.core.urlresolvers.reverse`, you don't need to
worry about the ``urlconf`` parameter. The function returns a
:class:`ResolverMatch` object that allows you
to access various meta-data about the resolved URL.

If the URL does not resolve, the function raises a
:exc:`~django.core.urlresolvers.Resolver404` exception (a subclass of
:class:`~django.http.Http404`) .

.. class:: ResolverMatch

    .. attribute:: ResolverMatch.func

        The view function that would be used to serve the URL

    .. attribute:: ResolverMatch.args

        The arguments that would be passed to the view function, as
        parsed from the URL.

    .. attribute:: ResolverMatch.kwargs

        The keyword arguments that would be passed to the view
        function, as parsed from the URL.

    .. attribute:: ResolverMatch.url_name

        The name of the URL pattern that matches the URL.

    .. attribute:: ResolverMatch.app_name

        The application namespace for the URL pattern that matches the
        URL.

    .. attribute:: ResolverMatch.app_names

        .. versionadded:: 1.9

        The list of individual namespace components in the full
        application namespace for the URL pattern that matches the URL.
        For example, if the ``app_name`` is ``'foo:bar'``, then ``app_names``
        will be ``['foo', 'bar']``.

    .. attribute:: ResolverMatch.namespace

        The instance namespace for the URL pattern that matches the
        URL.

    .. attribute:: ResolverMatch.namespaces

        The list of individual namespace components in the full
        instance namespace for the URL pattern that matches the URL.
        i.e., if the namespace is ``foo:bar``, then namespaces will be
        ``['foo', 'bar']``.

    .. attribute:: ResolverMatch.view_name

        The name of the view that matches the URL, including the namespace if
        there is one.

A :class:`ResolverMatch` object can then be interrogated to provide
information about the URL pattern that matches a URL::

    # Resolve a URL
    match = resolve('/some/path/')
    # Print the URL pattern that matches the URL
    print(match.url_name)

A :class:`ResolverMatch` object can also be assigned to a triple::

    func, args, kwargs = resolve('/some/path/')

One possible use of :func:`~django.core.urlresolvers.resolve` would be to test
whether a view would raise a ``Http404`` error before redirecting to it::

    from django.core.urlresolvers import resolve
    from django.http import HttpResponseRedirect, Http404
    from django.utils.six.moves.urllib.parse import urlparse

    def myview(request):
        next = request.META.get('HTTP_REFERER', None) or '/'
        response = HttpResponseRedirect(next)

        # modify the request and response as required, e.g. change locale
        # and set corresponding locale cookie

        view, args, kwargs = resolve(urlparse(next)[2])
        kwargs['request'] = request
        try:
            view(*args, **kwargs)
        except Http404:
            return HttpResponseRedirect('/')
        return response

get_script_prefix()
-------------------

.. function:: get_script_prefix()

Normally, you should always use :func:`~django.core.urlresolvers.reverse` to
define URLs within your application. However, if your application constructs
part of the URL hierarchy itself, you may occasionally need to generate URLs.
In that case, you need to be able to find the base URL of the Django project
within its Web server (normally, :func:`~django.core.urlresolvers.reverse`
takes care of this for you). In that case, you can call
``get_script_prefix()``, which will return the script prefix portion of the URL
for your Django project. If your Django project is at the root of its web
server, this is always ``"/"``.