Debian Codegraph @

docs/ref/urlresolvers.txt

raw
1 =================================
2 ``django.urls`` utility functions
3 =================================
4
5 .. module:: django.urls
6
7 ``reverse()``
8 =============
9
10 The ``reverse()`` function can be used to return an absolute path reference
11 for a given view and optional parameters, similar to the :ttag:`url` tag:
12
13 .. function:: reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None, *, query=None, fragment=None)
14
15 ``viewname`` can be a :ref:`URL pattern name <naming-url-patterns>` or the
16 callable view object used in the URLconf. For example, given the following
17 ``url``::
18
19 from news import views
20
21 path("archive/", views.archive, name="news-archive")
22
23 you can use any of the following to reverse the URL::
24
25 # using the named URL
26 reverse("news-archive")
27
28 # passing a callable object
29 # (This is discouraged because you can't reverse namespaced views this way.)
30 from news import views
31
32 reverse(views.archive)
33
34 If the URL accepts arguments, you may pass them in ``args``. For example::
35
36 from django.urls import reverse
37
38
39 def myview(request):
40 return HttpResponseRedirect(reverse("arch-summary", args=[1945]))
41
42 You can also pass ``kwargs`` instead of ``args``. For example:
43
44 .. code-block:: pycon
45
46 >>> reverse("admin:app_list", kwargs={"app_label": "auth"})
47 '/admin/auth/'
48
49 ``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.
50
51 If no match can be made, ``reverse()`` raises a
52 :class:`~django.urls.NoReverseMatch` exception.
53
54 The ``reverse()`` function can reverse a large variety of regular expression
55 patterns for URLs, but not every possible one. The main restriction at the
56 moment is that the pattern cannot contain alternative choices using the
57 vertical bar (``"|"``) character. You can quite happily use such patterns for
58 matching against incoming URLs and sending them off to views, but you cannot
59 reverse such patterns.
60
61 The ``current_app`` argument allows you to provide a hint to the resolver
62 indicating the application to which the currently executing view belongs.
63 This ``current_app`` argument is used as a hint to resolve application
64 namespaces into URLs on specific application instances, according to the
65 :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
66
67 The ``urlconf`` argument is the URLconf module containing the URL patterns to
68 use for reversing. By default, the root URLconf for the current thread is used.
69
70 The ``query`` keyword argument specifies parameters to be added to the returned
71 URL. It can accept an instance of :class:`~django.http.QueryDict` (such as
72 ``request.GET``) or any value compatible with :func:`urllib.parse.urlencode`.
73 The encoded query string is appended to the resolved URL, prefixed by a ``?``.
74
75 The ``fragment`` keyword argument specifies a fragment identifier to be
76 appended to the returned URL (that is, after the path and query string,
77 preceded by a ``#``).
78
79 For example:
80
81 .. code-block:: pycon
82
83 >>> from django.urls import reverse
84 >>> reverse("admin:index", query={"q": "biscuits", "page": 2}, fragment="results")
85 '/admin/?q=biscuits&page=2#results'
86 >>> reverse("admin:index", query=[("color", "blue"), ("color", 1), ("none", None)])
87 '/admin/?color=blue&color=1&none=None'
88 >>> reverse("admin:index", query={"has empty spaces": "also has empty spaces!"})
89 '/admin/?has+empty+spaces=also+has+empty+spaces%21'
90 >>> reverse("admin:index", fragment="no encoding is done")
91 '/admin/#no encoding is done'
92
93 .. versionchanged:: 5.2
94
95 The ``query`` and ``fragment`` arguments were added.
96
97 .. note::
98
99 The string returned by ``reverse()`` is already
100 :ref:`urlquoted <uri-and-iri-handling>`. For example:
101
102 .. code-block:: pycon
103
104 >>> reverse("cities", args=["Orléans"])
105 '.../Orl%C3%A9ans/'
106
107 Applying further encoding (such as :func:`urllib.parse.quote`) to the output
108 of ``reverse()`` may produce undesirable results.
109
110 .. admonition:: Reversing class-based views by view object
111
112 The view object can also be the result of calling
113 :meth:`~django.views.generic.base.View.as_view` if the same view object is
114 used in the URLConf. Following the original example, the view object could
115 be defined as:
116
117 .. code-block:: python
118 :caption: ``news/views.py``
119
120 from django.views import View
121
122
123 class ArchiveView(View): ...
124
125
126 archive = ArchiveView.as_view()
127
128 However, remember that namespaced views cannot be reversed by view object.
129
130 ``reverse_lazy()``
131 ==================
132
133 A lazily evaluated version of `reverse()`_.
134
135 .. function:: reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None, *, query=None, fragment=None)
136
137 It is useful for when you need to use a URL reversal before your project's
138 URLConf is loaded. Some common cases where this function is necessary are:
139
140 * providing a reversed URL as the ``url`` attribute of a generic class-based
141 view.
142
143 * providing a reversed URL to a decorator (such as the ``login_url`` argument
144 for the :func:`django.contrib.auth.decorators.permission_required`
145 decorator).
146
147 * providing a reversed URL as a default value for a parameter in a function's
148 signature.
149
150 .. versionchanged:: 5.2
151
152 The ``query`` and ``fragment`` arguments were added.
153
154 ``resolve()``
155 =============
156
157 The ``resolve()`` function can be used for resolving URL paths to the
158 corresponding view functions. It has the following signature:
159
160 .. function:: resolve(path, urlconf=None)
161
162 ``path`` is the URL path you want to resolve. As with
163 :func:`~django.urls.reverse`, you don't need to worry about the ``urlconf``
164 parameter. The function returns a :class:`ResolverMatch` object that allows you
165 to access various metadata about the resolved URL.
166
167 If the URL does not resolve, the function raises a
168 :exc:`~django.urls.Resolver404` exception (a subclass of
169 :class:`~django.http.Http404`) .
170
171 .. class:: ResolverMatch
172
173 .. attribute:: ResolverMatch.func
174
175 The view function that would be used to serve the URL
176
177 .. attribute:: ResolverMatch.args
178
179 The arguments that would be passed to the view function, as
180 parsed from the URL.
181
182 .. attribute:: ResolverMatch.kwargs
183
184 All keyword arguments that would be passed to the view function, i.e.
185 :attr:`~ResolverMatch.captured_kwargs` and
186 :attr:`~ResolverMatch.extra_kwargs`.
187
188 .. attribute:: ResolverMatch.captured_kwargs
189
190 The captured keyword arguments that would be passed to the view
191 function, as parsed from the URL.
192
193 .. attribute:: ResolverMatch.extra_kwargs
194
195 The additional keyword arguments that would be passed to the view
196 function.
197
198 .. attribute:: ResolverMatch.url_name
199
200 The name of the URL pattern that matches the URL.
201
202 .. attribute:: ResolverMatch.route
203
204 The route of the matching URL pattern.
205
206 For example, if ``path('users/<id>/', ...)`` is the matching pattern,
207 ``route`` will contain ``'users/<id>/'``.
208
209 .. attribute:: ResolverMatch.tried
210
211 The list of URL patterns tried before the URL either matched one or
212 exhausted available patterns.
213
214 .. attribute:: ResolverMatch.app_name
215
216 The application namespace for the URL pattern that matches the
217 URL.
218
219 .. attribute:: ResolverMatch.app_names
220
221 The list of individual namespace components in the full
222 application namespace for the URL pattern that matches the URL.
223 For example, if the ``app_name`` is ``'foo:bar'``, then ``app_names``
224 will be ``['foo', 'bar']``.
225
226 .. attribute:: ResolverMatch.namespace
227
228 The instance namespace for the URL pattern that matches the
229 URL.
230
231 .. attribute:: ResolverMatch.namespaces
232
233 The list of individual namespace components in the full
234 instance namespace for the URL pattern that matches the URL.
235 i.e., if the namespace is ``foo:bar``, then namespaces will be
236 ``['foo', 'bar']``.
237
238 .. attribute:: ResolverMatch.view_name
239
240 The name of the view that matches the URL, including the namespace if
241 there is one.
242
243 A :class:`ResolverMatch` object can then be interrogated to provide
244 information about the URL pattern that matches a URL::
245
246 # Resolve a URL
247 match = resolve("/some/path/")
248 # Print the URL pattern that matches the URL
249 print(match.url_name)
250
251 A :class:`ResolverMatch` object can also be assigned to a triple::
252
253 func, args, kwargs = resolve("/some/path/")
254
255 One possible use of :func:`~django.urls.resolve` would be to test whether a
256 view would raise a ``Http404`` error before redirecting to it::
257
258 from urllib.parse import urlsplit
259 from django.urls import resolve
260 from django.http import Http404, HttpResponseRedirect
261
262
263 def myview(request):
264 next = request.META.get("HTTP_REFERER", None) or "/"
265 response = HttpResponseRedirect(next)
266
267 # modify the request and response as required, e.g. change locale
268 # and set corresponding locale cookie
269
270 view, args, kwargs = resolve(urlsplit(next).path)
271 kwargs["request"] = request
272 try:
273 view(*args, **kwargs)
274 except Http404:
275 return HttpResponseRedirect("/")
276 return response
277
278 ``get_script_prefix()``
279 =======================
280
281 .. function:: get_script_prefix()
282
283 Normally, you should always use :func:`~django.urls.reverse` to define URLs
284 within your application. However, if your application constructs part of the
285 URL hierarchy itself, you may occasionally need to generate URLs. In that
286 case, you need to be able to find the base URL of the Django project within
287 its web server (normally, :func:`~django.urls.reverse` takes care of this for
288 you). In that case, you can call ``get_script_prefix()``, which will return
289 the script prefix portion of the URL for your Django project. If your Django
290 project is at the root of its web server, this is always ``"/"``.
291
292 .. warning::
293
294 This function **cannot** be used outside of the request-response cycle
295 since it relies on values initialized during that cycle.