|
1 ============== |
|
2 URL dispatcher |
|
3 ============== |
|
4 |
|
5 .. module:: django.core.urlresolvers |
|
6 |
|
7 A clean, elegant URL scheme is an important detail in a high-quality Web |
|
8 application. Django lets you design URLs however you want, with no framework |
|
9 limitations. |
|
10 |
|
11 There's no ``.php`` or ``.cgi`` required, and certainly none of that |
|
12 ``0,2097,1-1-1928,00`` nonsense. |
|
13 |
|
14 See `Cool URIs don't change`_, by World Wide Web creator Tim Berners-Lee, for |
|
15 excellent arguments on why URLs should be clean and usable. |
|
16 |
|
17 .. _Cool URIs don't change: http://www.w3.org/Provider/Style/URI |
|
18 |
|
19 Overview |
|
20 ======== |
|
21 |
|
22 To design URLs for an app, you create a Python module informally called a |
|
23 **URLconf** (URL configuration). This module is pure Python code and |
|
24 is a simple mapping between URL patterns (as simple regular expressions) to |
|
25 Python callback functions (your views). |
|
26 |
|
27 This mapping can be as short or as long as needed. It can reference other |
|
28 mappings. And, because it's pure Python code, it can be constructed |
|
29 dynamically. |
|
30 |
|
31 .. _how-django-processes-a-request: |
|
32 |
|
33 How Django processes a request |
|
34 ============================== |
|
35 |
|
36 When a user requests a page from your Django-powered site, this is the |
|
37 algorithm the system follows to determine which Python code to execute: |
|
38 |
|
39 1. Django determines the root URLconf module to use. Ordinarily, |
|
40 this is the value of the :setting:`ROOT_URLCONF` setting, but if the incoming |
|
41 ``HttpRequest`` object has an attribute called ``urlconf`` (set by |
|
42 middleware :ref:`request processing <request-middleware>`), its value |
|
43 will be used in place of the :setting:`ROOT_URLCONF` setting. |
|
44 |
|
45 2. Django loads that Python module and looks for the variable |
|
46 ``urlpatterns``. This should be a Python list, in the format returned by |
|
47 the function :func:`django.conf.urls.defaults.patterns`. |
|
48 |
|
49 3. Django runs through each URL pattern, in order, and stops at the first |
|
50 one that matches the requested URL. |
|
51 |
|
52 4. Once one of the regexes matches, Django imports and calls the given |
|
53 view, which is a simple Python function. The view gets passed an |
|
54 :class:`~django.http.HttpRequest` as its first argument and any values |
|
55 captured in the regex as remaining arguments. |
|
56 |
|
57 Example |
|
58 ======= |
|
59 |
|
60 Here's a sample URLconf:: |
|
61 |
|
62 from django.conf.urls.defaults import * |
|
63 |
|
64 urlpatterns = patterns('', |
|
65 (r'^articles/2003/$', 'news.views.special_case_2003'), |
|
66 (r'^articles/(\d{4})/$', 'news.views.year_archive'), |
|
67 (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'), |
|
68 (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'), |
|
69 ) |
|
70 |
|
71 Notes: |
|
72 |
|
73 * ``from django.conf.urls.defaults import *`` makes the ``patterns()`` |
|
74 function available. |
|
75 |
|
76 * To capture a value from the URL, just put parenthesis around it. |
|
77 |
|
78 * There's no need to add a leading slash, because every URL has that. For |
|
79 example, it's ``^articles``, not ``^/articles``. |
|
80 |
|
81 * The ``'r'`` in front of each regular expression string is optional but |
|
82 recommended. It tells Python that a string is "raw" -- that nothing in |
|
83 the string should be escaped. See `Dive Into Python's explanation`_. |
|
84 |
|
85 Example requests: |
|
86 |
|
87 * A request to ``/articles/2005/03/`` would match the third entry in the |
|
88 list. Django would call the function |
|
89 ``news.views.month_archive(request, '2005', '03')``. |
|
90 |
|
91 * ``/articles/2005/3/`` would not match any URL patterns, because the |
|
92 third entry in the list requires two digits for the month. |
|
93 |
|
94 * ``/articles/2003/`` would match the first pattern in the list, not the |
|
95 second one, because the patterns are tested in order, and the first one |
|
96 is the first test to pass. Feel free to exploit the ordering to insert |
|
97 special cases like this. |
|
98 |
|
99 * ``/articles/2003`` would not match any of these patterns, because each |
|
100 pattern requires that the URL end with a slash. |
|
101 |
|
102 * ``/articles/2003/03/3/`` would match the final pattern. Django would call |
|
103 the function ``news.views.article_detail(request, '2003', '03', '3')``. |
|
104 |
|
105 .. _Dive Into Python's explanation: http://diveintopython.org/regular_expressions/street_addresses.html#re.matching.2.3 |
|
106 |
|
107 Named groups |
|
108 ============ |
|
109 |
|
110 The above example used simple, *non-named* regular-expression groups (via |
|
111 parenthesis) to capture bits of the URL and pass them as *positional* arguments |
|
112 to a view. In more advanced usage, it's possible to use *named* |
|
113 regular-expression groups to capture URL bits and pass them as *keyword* |
|
114 arguments to a view. |
|
115 |
|
116 In Python regular expressions, the syntax for named regular-expression groups |
|
117 is ``(?P<name>pattern)``, where ``name`` is the name of the group and |
|
118 ``pattern`` is some pattern to match. |
|
119 |
|
120 Here's the above example URLconf, rewritten to use named groups:: |
|
121 |
|
122 urlpatterns = patterns('', |
|
123 (r'^articles/2003/$', 'news.views.special_case_2003'), |
|
124 (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'), |
|
125 (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive'), |
|
126 (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'news.views.article_detail'), |
|
127 ) |
|
128 |
|
129 This accomplishes exactly the same thing as the previous example, with one |
|
130 subtle difference: The captured values are passed to view functions as keyword |
|
131 arguments rather than positional arguments. For example: |
|
132 |
|
133 * A request to ``/articles/2005/03/`` would call the function |
|
134 ``news.views.month_archive(request, year='2005', month='03')``, instead |
|
135 of ``news.views.month_archive(request, '2005', '03')``. |
|
136 |
|
137 * A request to ``/articles/2003/03/3/`` would call the function |
|
138 ``news.views.article_detail(request, year='2003', month='03', day='3')``. |
|
139 |
|
140 In practice, this means your URLconfs are slightly more explicit and less prone |
|
141 to argument-order bugs -- and you can reorder the arguments in your views' |
|
142 function definitions. Of course, these benefits come at the cost of brevity; |
|
143 some developers find the named-group syntax ugly and too verbose. |
|
144 |
|
145 The matching/grouping algorithm |
|
146 ------------------------------- |
|
147 |
|
148 Here's the algorithm the URLconf parser follows, with respect to named groups |
|
149 vs. non-named groups in a regular expression: |
|
150 |
|
151 If there are any named arguments, it will use those, ignoring non-named arguments. |
|
152 Otherwise, it will pass all non-named arguments as positional arguments. |
|
153 |
|
154 In both cases, it will pass any extra keyword arguments as keyword arguments. |
|
155 See "Passing extra options to view functions" below. |
|
156 |
|
157 What the URLconf searches against |
|
158 ================================= |
|
159 |
|
160 The URLconf searches against the requested URL, as a normal Python string. This |
|
161 does not include GET or POST parameters, or the domain name. |
|
162 |
|
163 For example, in a request to ``http://www.example.com/myapp/``, the URLconf |
|
164 will look for ``myapp/``. |
|
165 |
|
166 In a request to ``http://www.example.com/myapp/?page=3``, the URLconf will look |
|
167 for ``myapp/``. |
|
168 |
|
169 The URLconf doesn't look at the request method. In other words, all request |
|
170 methods -- ``POST``, ``GET``, ``HEAD``, etc. -- will be routed to the same |
|
171 function for the same URL. |
|
172 |
|
173 Syntax of the urlpatterns variable |
|
174 ================================== |
|
175 |
|
176 ``urlpatterns`` should be a Python list, in the format returned by the function |
|
177 :func:`django.conf.urls.defaults.patterns`. Always use ``patterns()`` to create |
|
178 the ``urlpatterns`` variable. |
|
179 |
|
180 Convention is to use ``from django.conf.urls.defaults import *`` at the top of |
|
181 your URLconf. This gives your module access to these objects: |
|
182 |
|
183 .. module:: django.conf.urls.defaults |
|
184 |
|
185 patterns |
|
186 -------- |
|
187 |
|
188 .. function:: patterns(prefix, pattern_description, ...) |
|
189 |
|
190 A function that takes a prefix, and an arbitrary number of URL patterns, and |
|
191 returns a list of URL patterns in the format Django needs. |
|
192 |
|
193 The first argument to ``patterns()`` is a string ``prefix``. See |
|
194 `The view prefix`_ below. |
|
195 |
|
196 The remaining arguments should be tuples in this format:: |
|
197 |
|
198 (regular expression, Python callback function [, optional dictionary [, optional name]]) |
|
199 |
|
200 ...where ``optional dictionary`` and ``optional name`` are optional. (See |
|
201 `Passing extra options to view functions`_ below.) |
|
202 |
|
203 .. note:: |
|
204 Because `patterns()` is a function call, it accepts a maximum of 255 |
|
205 arguments (URL patterns, in this case). This is a limit for all Python |
|
206 function calls. This is rarely a problem in practice, because you'll |
|
207 typically structure your URL patterns modularly by using `include()` |
|
208 sections. However, on the off-chance you do hit the 255-argument limit, |
|
209 realize that `patterns()` returns a Python list, so you can split up the |
|
210 construction of the list. |
|
211 |
|
212 :: |
|
213 |
|
214 urlpatterns = patterns('', |
|
215 ... |
|
216 ) |
|
217 urlpatterns += patterns('', |
|
218 ... |
|
219 ) |
|
220 |
|
221 Python lists have unlimited size, so there's no limit to how many URL |
|
222 patterns you can construct. The only limit is that you can only create 254 |
|
223 at a time (the 255th argument is the initial prefix argument). |
|
224 |
|
225 url |
|
226 --- |
|
227 |
|
228 .. versionadded:: 1.0 |
|
229 |
|
230 .. function:: url(regex, view, kwargs=None, name=None, prefix='') |
|
231 |
|
232 You can use the ``url()`` function, instead of a tuple, as an argument to |
|
233 ``patterns()``. This is convenient if you want to specify a name without the |
|
234 optional extra arguments dictionary. For example:: |
|
235 |
|
236 urlpatterns = patterns('', |
|
237 url(r'^index/$', index_view, name="main-view"), |
|
238 ... |
|
239 ) |
|
240 |
|
241 This function takes five arguments, most of which are optional:: |
|
242 |
|
243 url(regex, view, kwargs=None, name=None, prefix='') |
|
244 |
|
245 See `Naming URL patterns`_ for why the ``name`` parameter is useful. |
|
246 |
|
247 The ``prefix`` parameter has the same meaning as the first argument to |
|
248 ``patterns()`` and is only relevant when you're passing a string as the |
|
249 ``view`` parameter. |
|
250 |
|
251 handler404 |
|
252 ---------- |
|
253 |
|
254 .. data:: handler404 |
|
255 |
|
256 A callable, or a string representing the full Python import path to the view |
|
257 that should be called if none of the URL patterns match. |
|
258 |
|
259 By default, this is ``'django.views.defaults.page_not_found'``. That default |
|
260 value should suffice. |
|
261 |
|
262 .. versionchanged:: 1.2 |
|
263 Previous versions of Django only accepted strings representing import paths. |
|
264 |
|
265 handler500 |
|
266 ---------- |
|
267 |
|
268 .. data:: handler500 |
|
269 |
|
270 A callable, or a string representing the full Python import path to the view |
|
271 that should be called in case of server errors. Server errors happen when you |
|
272 have runtime errors in view code. |
|
273 |
|
274 By default, this is ``'django.views.defaults.server_error'``. That default |
|
275 value should suffice. |
|
276 |
|
277 .. versionchanged:: 1.2 |
|
278 Previous versions of Django only accepted strings representing import paths. |
|
279 |
|
280 include |
|
281 ------- |
|
282 |
|
283 .. function:: include(<module or pattern_list>) |
|
284 |
|
285 A function that takes a full Python import path to another URLconf module that |
|
286 should be "included" in this place. |
|
287 |
|
288 .. versionadded:: 1.1 |
|
289 |
|
290 :func:`include` also accepts as an argument an iterable that returns URL |
|
291 patterns. |
|
292 |
|
293 See `Including other URLconfs`_ below. |
|
294 |
|
295 Notes on capturing text in URLs |
|
296 =============================== |
|
297 |
|
298 Each captured argument is sent to the view as a plain Python string, regardless |
|
299 of what sort of match the regular expression makes. For example, in this |
|
300 URLconf line:: |
|
301 |
|
302 (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'), |
|
303 |
|
304 ...the ``year`` argument to ``news.views.year_archive()`` will be a string, not |
|
305 an integer, even though the ``\d{4}`` will only match integer strings. |
|
306 |
|
307 A convenient trick is to specify default parameters for your views' arguments. |
|
308 Here's an example URLconf and view:: |
|
309 |
|
310 # URLconf |
|
311 urlpatterns = patterns('', |
|
312 (r'^blog/$', 'blog.views.page'), |
|
313 (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'), |
|
314 ) |
|
315 |
|
316 # View (in blog/views.py) |
|
317 def page(request, num="1"): |
|
318 # Output the appropriate page of blog entries, according to num. |
|
319 |
|
320 In the above example, both URL patterns point to the same view -- |
|
321 ``blog.views.page`` -- but the first pattern doesn't capture anything from the |
|
322 URL. If the first pattern matches, the ``page()`` function will use its |
|
323 default argument for ``num``, ``"1"``. If the second pattern matches, |
|
324 ``page()`` will use whatever ``num`` value was captured by the regex. |
|
325 |
|
326 Performance |
|
327 =========== |
|
328 |
|
329 Each regular expression in a ``urlpatterns`` is compiled the first time it's |
|
330 accessed. This makes the system blazingly fast. |
|
331 |
|
332 The view prefix |
|
333 =============== |
|
334 |
|
335 You can specify a common prefix in your ``patterns()`` call, to cut down on |
|
336 code duplication. |
|
337 |
|
338 Here's the example URLconf from the :doc:`Django overview </intro/overview>`:: |
|
339 |
|
340 from django.conf.urls.defaults import * |
|
341 |
|
342 urlpatterns = patterns('', |
|
343 (r'^articles/(\d{4})/$', 'news.views.year_archive'), |
|
344 (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'), |
|
345 (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'), |
|
346 ) |
|
347 |
|
348 In this example, each view has a common prefix -- ``'news.views'``. |
|
349 Instead of typing that out for each entry in ``urlpatterns``, you can use the |
|
350 first argument to the ``patterns()`` function to specify a prefix to apply to |
|
351 each view function. |
|
352 |
|
353 With this in mind, the above example can be written more concisely as:: |
|
354 |
|
355 from django.conf.urls.defaults import * |
|
356 |
|
357 urlpatterns = patterns('news.views', |
|
358 (r'^articles/(\d{4})/$', 'year_archive'), |
|
359 (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'), |
|
360 (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'), |
|
361 ) |
|
362 |
|
363 Note that you don't put a trailing dot (``"."``) in the prefix. Django puts |
|
364 that in automatically. |
|
365 |
|
366 Multiple view prefixes |
|
367 ---------------------- |
|
368 |
|
369 In practice, you'll probably end up mixing and matching views to the point |
|
370 where the views in your ``urlpatterns`` won't have a common prefix. However, |
|
371 you can still take advantage of the view prefix shortcut to remove duplication. |
|
372 Just add multiple ``patterns()`` objects together, like this: |
|
373 |
|
374 Old:: |
|
375 |
|
376 from django.conf.urls.defaults import * |
|
377 |
|
378 urlpatterns = patterns('', |
|
379 (r'^$', 'django.views.generic.date_based.archive_index'), |
|
380 (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'django.views.generic.date_based.archive_month'), |
|
381 (r'^tag/(?P<tag>\w+)/$', 'weblog.views.tag'), |
|
382 ) |
|
383 |
|
384 New:: |
|
385 |
|
386 from django.conf.urls.defaults import * |
|
387 |
|
388 urlpatterns = patterns('django.views.generic.date_based', |
|
389 (r'^$', 'archive_index'), |
|
390 (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'), |
|
391 ) |
|
392 |
|
393 urlpatterns += patterns('weblog.views', |
|
394 (r'^tag/(?P<tag>\w+)/$', 'tag'), |
|
395 ) |
|
396 |
|
397 Including other URLconfs |
|
398 ======================== |
|
399 |
|
400 At any point, your ``urlpatterns`` can "include" other URLconf modules. This |
|
401 essentially "roots" a set of URLs below other ones. |
|
402 |
|
403 For example, here's the URLconf for the `Django Web site`_ itself. It includes a |
|
404 number of other URLconfs:: |
|
405 |
|
406 from django.conf.urls.defaults import * |
|
407 |
|
408 urlpatterns = patterns('', |
|
409 (r'^weblog/', include('django_website.apps.blog.urls.blog')), |
|
410 (r'^documentation/', include('django_website.apps.docs.urls.docs')), |
|
411 (r'^comments/', include('django.contrib.comments.urls')), |
|
412 ) |
|
413 |
|
414 Note that the regular expressions in this example don't have a ``$`` |
|
415 (end-of-string match character) but do include a trailing slash. Whenever |
|
416 Django encounters ``include()``, it chops off whatever part of the URL matched |
|
417 up to that point and sends the remaining string to the included URLconf for |
|
418 further processing. |
|
419 |
|
420 .. versionadded:: 1.1 |
|
421 |
|
422 Another possibility is to include additional URL patterns not by specifying the |
|
423 URLconf Python module defining them as the `include`_ argument but by using |
|
424 directly the pattern list as returned by `patterns`_ instead. For example:: |
|
425 |
|
426 from django.conf.urls.defaults import * |
|
427 |
|
428 extra_patterns = patterns('', |
|
429 url(r'reports/(?P<id>\d+)/$', 'credit.views.report', name='credit-reports'), |
|
430 url(r'charge/$', 'credit.views.charge', name='credit-charge'), |
|
431 ) |
|
432 |
|
433 urlpatterns = patterns('', |
|
434 url(r'^$', 'apps.main.views.homepage', name='site-homepage'), |
|
435 (r'^help/', include('apps.help.urls')), |
|
436 (r'^credit/', include(extra_patterns)), |
|
437 ) |
|
438 |
|
439 This approach can be seen in use when you deploy an instance of the Django |
|
440 Admin application. The Django Admin is deployed as instances of a |
|
441 :class:`~django.contrib.admin.AdminSite`; each |
|
442 :class:`~django.contrib.admin.AdminSite` instance has an attribute ``urls`` |
|
443 that returns the url patterns available to that instance. It is this attribute |
|
444 that you ``include()`` into your projects ``urlpatterns`` when you deploy the |
|
445 admin instance. |
|
446 |
|
447 .. _`Django Web site`: http://www.djangoproject.com/ |
|
448 |
|
449 Captured parameters |
|
450 ------------------- |
|
451 |
|
452 An included URLconf receives any captured parameters from parent URLconfs, so |
|
453 the following example is valid:: |
|
454 |
|
455 # In settings/urls/main.py |
|
456 urlpatterns = patterns('', |
|
457 (r'^(?P<username>\w+)/blog/', include('foo.urls.blog')), |
|
458 ) |
|
459 |
|
460 # In foo/urls/blog.py |
|
461 urlpatterns = patterns('foo.views', |
|
462 (r'^$', 'blog.index'), |
|
463 (r'^archive/$', 'blog.archive'), |
|
464 ) |
|
465 |
|
466 In the above example, the captured ``"username"`` variable is passed to the |
|
467 included URLconf, as expected. |
|
468 |
|
469 .. _topics-http-defining-url-namespaces: |
|
470 |
|
471 Defining URL Namespaces |
|
472 ----------------------- |
|
473 |
|
474 When you need to deploy multiple instances of a single application, it can be |
|
475 helpful to be able to differentiate between instances. This is especially |
|
476 important when using :ref:`named URL patterns <naming-url-patterns>`, since |
|
477 multiple instances of a single application will share named URLs. Namespaces |
|
478 provide a way to tell these named URLs apart. |
|
479 |
|
480 A URL namespace comes in two parts, both of which are strings: |
|
481 |
|
482 * An **application namespace**. This describes the name of the application |
|
483 that is being deployed. Every instance of a single application will have |
|
484 the same application namespace. For example, Django's admin application |
|
485 has the somewhat predictable application namespace of ``admin``. |
|
486 |
|
487 * An **instance namespace**. This identifies a specific instance of an |
|
488 application. Instance namespaces should be unique across your entire |
|
489 project. However, an instance namespace can be the same as the |
|
490 application namespace. This is used to specify a default instance of an |
|
491 application. For example, the default Django Admin instance has an |
|
492 instance namespace of ``admin``. |
|
493 |
|
494 URL Namespaces can be specified in two ways. |
|
495 |
|
496 Firstly, you can provide the application and instance namespace as arguments |
|
497 to ``include()`` when you construct your URL patterns. For example,:: |
|
498 |
|
499 (r'^help/', include('apps.help.urls', namespace='foo', app_name='bar')), |
|
500 |
|
501 This will include the URLs defined in ``apps.help.urls`` into the application |
|
502 namespace ``bar``, with the instance namespace ``foo``. |
|
503 |
|
504 Secondly, you can include an object that contains embedded namespace data. If |
|
505 you ``include()`` a ``patterns`` object, that object will be added to the |
|
506 global namespace. However, you can also ``include()`` an object that contains |
|
507 a 3-tuple containing:: |
|
508 |
|
509 (<patterns object>, <application namespace>, <instance namespace>) |
|
510 |
|
511 This will include the nominated URL patterns into the given application and |
|
512 instance namespace. For example, the ``urls`` attribute of Django's |
|
513 :class:`~django.contrib.admin.AdminSite` object returns a 3-tuple that contains |
|
514 all the patterns in an admin site, plus the name of the admin instance, and the |
|
515 application namespace ``admin``. |
|
516 |
|
517 Once you have defined namespaced URLs, you can reverse them. For details on |
|
518 reversing namespaced urls, see the documentation on :ref:`reversing namespaced |
|
519 URLs <topics-http-reversing-url-namespaces>`. |
|
520 |
|
521 Passing extra options to view functions |
|
522 ======================================= |
|
523 |
|
524 URLconfs have a hook that lets you pass extra arguments to your view functions, |
|
525 as a Python dictionary. |
|
526 |
|
527 Any URLconf tuple can have an optional third element, which should be a |
|
528 dictionary of extra keyword arguments to pass to the view function. |
|
529 |
|
530 For example:: |
|
531 |
|
532 urlpatterns = patterns('blog.views', |
|
533 (r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}), |
|
534 ) |
|
535 |
|
536 In this example, for a request to ``/blog/2005/``, Django will call the |
|
537 ``blog.views.year_archive()`` view, passing it these keyword arguments:: |
|
538 |
|
539 year='2005', foo='bar' |
|
540 |
|
541 This technique is used in :doc:`generic views </ref/generic-views>` and in the |
|
542 :doc:`syndication framework </ref/contrib/syndication>` to pass metadata and |
|
543 options to views. |
|
544 |
|
545 .. admonition:: Dealing with conflicts |
|
546 |
|
547 It's possible to have a URL pattern which captures named keyword arguments, |
|
548 and also passes arguments with the same names in its dictionary of extra |
|
549 arguments. When this happens, the arguments in the dictionary will be used |
|
550 instead of the arguments captured in the URL. |
|
551 |
|
552 Passing extra options to ``include()`` |
|
553 -------------------------------------- |
|
554 |
|
555 Similarly, you can pass extra options to ``include()``. When you pass extra |
|
556 options to ``include()``, *each* line in the included URLconf will be passed |
|
557 the extra options. |
|
558 |
|
559 For example, these two URLconf sets are functionally identical: |
|
560 |
|
561 Set one:: |
|
562 |
|
563 # main.py |
|
564 urlpatterns = patterns('', |
|
565 (r'^blog/', include('inner'), {'blogid': 3}), |
|
566 ) |
|
567 |
|
568 # inner.py |
|
569 urlpatterns = patterns('', |
|
570 (r'^archive/$', 'mysite.views.archive'), |
|
571 (r'^about/$', 'mysite.views.about'), |
|
572 ) |
|
573 |
|
574 Set two:: |
|
575 |
|
576 # main.py |
|
577 urlpatterns = patterns('', |
|
578 (r'^blog/', include('inner')), |
|
579 ) |
|
580 |
|
581 # inner.py |
|
582 urlpatterns = patterns('', |
|
583 (r'^archive/$', 'mysite.views.archive', {'blogid': 3}), |
|
584 (r'^about/$', 'mysite.views.about', {'blogid': 3}), |
|
585 ) |
|
586 |
|
587 Note that extra options will *always* be passed to *every* line in the included |
|
588 URLconf, regardless of whether the line's view actually accepts those options |
|
589 as valid. For this reason, this technique is only useful if you're certain that |
|
590 every view in the included URLconf accepts the extra options you're passing. |
|
591 |
|
592 Passing callable objects instead of strings |
|
593 =========================================== |
|
594 |
|
595 Some developers find it more natural to pass the actual Python function object |
|
596 rather than a string containing the path to its module. This alternative is |
|
597 supported -- you can pass any callable object as the view. |
|
598 |
|
599 For example, given this URLconf in "string" notation:: |
|
600 |
|
601 urlpatterns = patterns('', |
|
602 (r'^archive/$', 'mysite.views.archive'), |
|
603 (r'^about/$', 'mysite.views.about'), |
|
604 (r'^contact/$', 'mysite.views.contact'), |
|
605 ) |
|
606 |
|
607 You can accomplish the same thing by passing objects rather than strings. Just |
|
608 be sure to import the objects:: |
|
609 |
|
610 from mysite.views import archive, about, contact |
|
611 |
|
612 urlpatterns = patterns('', |
|
613 (r'^archive/$', archive), |
|
614 (r'^about/$', about), |
|
615 (r'^contact/$', contact), |
|
616 ) |
|
617 |
|
618 The following example is functionally identical. It's just a bit more compact |
|
619 because it imports the module that contains the views, rather than importing |
|
620 each view individually:: |
|
621 |
|
622 from mysite import views |
|
623 |
|
624 urlpatterns = patterns('', |
|
625 (r'^archive/$', views.archive), |
|
626 (r'^about/$', views.about), |
|
627 (r'^contact/$', views.contact), |
|
628 ) |
|
629 |
|
630 The style you use is up to you. |
|
631 |
|
632 Note that if you use this technique -- passing objects rather than strings -- |
|
633 the view prefix (as explained in "The view prefix" above) will have no effect. |
|
634 |
|
635 .. _naming-url-patterns: |
|
636 |
|
637 Naming URL patterns |
|
638 =================== |
|
639 |
|
640 .. versionadded:: 1.0 |
|
641 |
|
642 It's fairly common to use the same view function in multiple URL patterns in |
|
643 your URLconf. For example, these two URL patterns both point to the ``archive`` |
|
644 view:: |
|
645 |
|
646 urlpatterns = patterns('', |
|
647 (r'^archive/(\d{4})/$', archive), |
|
648 (r'^archive-summary/(\d{4})/$', archive, {'summary': True}), |
|
649 ) |
|
650 |
|
651 This is completely valid, but it leads to problems when you try to do reverse |
|
652 URL matching (through the ``permalink()`` decorator or the :ttag:`url` template |
|
653 tag). Continuing this example, if you wanted to retrieve the URL for the |
|
654 ``archive`` view, Django's reverse URL matcher would get confused, because *two* |
|
655 URLpatterns point at that view. |
|
656 |
|
657 To solve this problem, Django supports **named URL patterns**. That is, you can |
|
658 give a name to a URL pattern in order to distinguish it from other patterns |
|
659 using the same view and parameters. Then, you can use this name in reverse URL |
|
660 matching. |
|
661 |
|
662 Here's the above example, rewritten to use named URL patterns:: |
|
663 |
|
664 urlpatterns = patterns('', |
|
665 url(r'^archive/(\d{4})/$', archive, name="full-archive"), |
|
666 url(r'^archive-summary/(\d{4})/$', archive, {'summary': True}, "arch-summary"), |
|
667 ) |
|
668 |
|
669 With these names in place (``full-archive`` and ``arch-summary``), you can |
|
670 target each pattern individually by using its name: |
|
671 |
|
672 .. code-block:: html+django |
|
673 |
|
674 {% url arch-summary 1945 %} |
|
675 {% url full-archive 2007 %} |
|
676 |
|
677 Even though both URL patterns refer to the ``archive`` view here, using the |
|
678 ``name`` parameter to ``url()`` allows you to tell them apart in templates. |
|
679 |
|
680 The string used for the URL name can contain any characters you like. You are |
|
681 not restricted to valid Python names. |
|
682 |
|
683 .. note:: |
|
684 |
|
685 When you name your URL patterns, make sure you use names that are unlikely |
|
686 to clash with any other application's choice of names. If you call your URL |
|
687 pattern ``comment``, and another application does the same thing, there's |
|
688 no guarantee which URL will be inserted into your template when you use |
|
689 this name. |
|
690 |
|
691 Putting a prefix on your URL names, perhaps derived from the application |
|
692 name, will decrease the chances of collision. We recommend something like |
|
693 ``myapp-comment`` instead of ``comment``. |
|
694 |
|
695 .. _topics-http-reversing-url-namespaces: |
|
696 |
|
697 URL namespaces |
|
698 -------------- |
|
699 |
|
700 .. versionadded:: 1.1 |
|
701 |
|
702 Namespaced URLs are specified using the ``:`` operator. For example, the main |
|
703 index page of the admin application is referenced using ``admin:index``. This |
|
704 indicates a namespace of ``admin``, and a named URL of ``index``. |
|
705 |
|
706 Namespaces can also be nested. The named URL ``foo:bar:whiz`` would look for |
|
707 a pattern named ``whiz`` in the namespace ``bar`` that is itself defined within |
|
708 the top-level namespace ``foo``. |
|
709 |
|
710 When given a namespaced URL (e.g. ``myapp:index``) to resolve, Django splits |
|
711 the fully qualified name into parts, and then tries the following lookup: |
|
712 |
|
713 1. First, Django looks for a matching application namespace (in this |
|
714 example, ``myapp``). This will yield a list of instances of that |
|
715 application. |
|
716 |
|
717 2. If there is a *current* application defined, Django finds and returns |
|
718 the URL resolver for that instance. The *current* application can be |
|
719 specified as an attribute on the template context - applications that |
|
720 expect to have multiple deployments should set the ``current_app`` |
|
721 attribute on any ``Context`` or ``RequestContext`` that is used to |
|
722 render a template. |
|
723 |
|
724 The current application can also be specified manually as an argument |
|
725 to the :func:`reverse()` function. |
|
726 |
|
727 3. If there is no current application. Django looks for a default |
|
728 application instance. The default application instance is the instance |
|
729 that has an instance namespace matching the application namespace (in |
|
730 this example, an instance of the ``myapp`` called ``myapp``). |
|
731 |
|
732 4. If there is no default application instance, Django will pick the last |
|
733 deployed instance of the application, whatever its instance name may be. |
|
734 |
|
735 5. If the provided namespace doesn't match an application namespace in |
|
736 step 1, Django will attempt a direct lookup of the namespace as an |
|
737 instance namespace. |
|
738 |
|
739 If there are nested namespaces, these steps are repeated for each part of the |
|
740 namespace until only the view name is unresolved. The view name will then be |
|
741 resolved into a URL in the namespace that has been found. |
|
742 |
|
743 To show this resolution strategy in action, consider an example of two instances |
|
744 of ``myapp``: one called ``foo``, and one called ``bar``. ``myapp`` has a main |
|
745 index page with a URL named `index`. Using this setup, the following lookups are |
|
746 possible: |
|
747 |
|
748 * If one of the instances is current - say, if we were rendering a utility page |
|
749 in the instance ``bar`` - ``myapp:index`` will resolve to the index page of |
|
750 the instance ``bar``. |
|
751 |
|
752 * If there is no current instance - say, if we were rendering a page |
|
753 somewhere else on the site - ``myapp:index`` will resolve to the last |
|
754 registered instance of ``myapp``. Since there is no default instance, |
|
755 the last instance of ``myapp`` that is registered will be used. This could |
|
756 be ``foo`` or ``bar``, depending on the order they are introduced into the |
|
757 urlpatterns of the project. |
|
758 |
|
759 * ``foo:index`` will always resolve to the index page of the instance ``foo``. |
|
760 |
|
761 If there was also a default instance - i.e., an instance named `myapp` - the |
|
762 following would happen: |
|
763 |
|
764 * If one of the instances is current - say, if we were rendering a utility page |
|
765 in the instance ``bar`` - ``myapp:index`` will resolve to the index page of |
|
766 the instance ``bar``. |
|
767 |
|
768 * If there is no current instance - say, if we were rendering a page somewhere |
|
769 else on the site - ``myapp:index`` will resolve to the index page of the |
|
770 default instance. |
|
771 |
|
772 * ``foo:index`` will again resolve to the index page of the instance ``foo``. |
|
773 |
|
774 |
|
775 Utility methods |
|
776 =============== |
|
777 |
|
778 reverse() |
|
779 --------- |
|
780 |
|
781 If you need to use something similar to the :ttag:`url` template tag in |
|
782 your code, Django provides the following method (in the |
|
783 ``django.core.urlresolvers`` module): |
|
784 |
|
785 .. function:: reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None) |
|
786 |
|
787 ``viewname`` is either the function name (either a function reference, or the |
|
788 string version of the name, if you used that form in ``urlpatterns``) or the |
|
789 `URL pattern name`_. Normally, you won't need to worry about the |
|
790 ``urlconf`` parameter and will only pass in the positional and keyword |
|
791 arguments to use in the URL matching. For example:: |
|
792 |
|
793 from django.core.urlresolvers import reverse |
|
794 |
|
795 def myview(request): |
|
796 return HttpResponseRedirect(reverse('arch-summary', args=[1945])) |
|
797 |
|
798 .. _URL pattern name: `Naming URL patterns`_ |
|
799 |
|
800 The ``reverse()`` function can reverse a large variety of regular expression |
|
801 patterns for URLs, but not every possible one. The main restriction at the |
|
802 moment is that the pattern cannot contain alternative choices using the |
|
803 vertical bar (``"|"``) character. You can quite happily use such patterns for |
|
804 matching against incoming URLs and sending them off to views, but you cannot |
|
805 reverse such patterns. |
|
806 |
|
807 .. versionadded:: 1.1 |
|
808 |
|
809 The ``current_app`` argument allows you to provide a hint to the resolver |
|
810 indicating the application to which the currently executing view belongs. |
|
811 This ``current_app`` argument is used as a hint to resolve application |
|
812 namespaces into URLs on specific application instances, according to the |
|
813 :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`. |
|
814 |
|
815 .. admonition:: Make sure your views are all correct. |
|
816 |
|
817 As part of working out which URL names map to which patterns, the |
|
818 ``reverse()`` function has to import all of your URLconf files and examine |
|
819 the name of each view. This involves importing each view function. If |
|
820 there are *any* errors whilst importing any of your view functions, it |
|
821 will cause ``reverse()`` to raise an error, even if that view function is |
|
822 not the one you are trying to reverse. |
|
823 |
|
824 Make sure that any views you reference in your URLconf files exist and can |
|
825 be imported correctly. Do not include lines that reference views you |
|
826 haven't written yet, because those views will not be importable. |
|
827 |
|
828 resolve() |
|
829 --------- |
|
830 |
|
831 The :func:`django.core.urlresolvers.resolve` function can be used for resolving |
|
832 URL paths to the corresponding view functions. It has the following signature: |
|
833 |
|
834 .. function:: resolve(path, urlconf=None) |
|
835 |
|
836 ``path`` is the URL path you want to resolve. As with |
|
837 :func:`~django.core.urlresolvers.reverse`, you don't need to |
|
838 worry about the ``urlconf`` parameter. The function returns |
|
839 the triple (view function, arguments, keyword arguments). |
|
840 |
|
841 If the URL does not resolve, the function raises an |
|
842 :class:`~django.http.Http404` exception. |
|
843 |
|
844 For example, it can be used for testing if a view would raise a ``Http404`` |
|
845 error before redirecting to it:: |
|
846 |
|
847 from urlparse import urlparse |
|
848 from django.core.urlresolvers import resolve |
|
849 from django.http import HttpResponseRedirect, Http404 |
|
850 |
|
851 def myview(request): |
|
852 next = request.META.get('HTTP_REFERER', None) or '/' |
|
853 response = HttpResponseRedirect(next) |
|
854 |
|
855 # modify the request and response as required, e.g. change locale |
|
856 # and set corresponding locale cookie |
|
857 |
|
858 view, args, kwargs = resolve(urlparse(next)[2]) |
|
859 kwargs['request'] = request |
|
860 try: |
|
861 view(*args, **kwargs) |
|
862 except Http404: |
|
863 return HttpResponseRedirect('/') |
|
864 return response |
|
865 |
|
866 permalink() |
|
867 ----------- |
|
868 |
|
869 The :func:`django.db.models.permalink` decorator is useful for writing short |
|
870 methods that return a full URL path. For example, a model's |
|
871 ``get_absolute_url()`` method. See :func:`django.db.models.permalink` for more. |
|
872 |
|
873 get_script_prefix() |
|
874 ------------------- |
|
875 |
|
876 .. function:: get_script_prefix() |
|
877 |
|
878 .. versionadded:: 1.0 |
|
879 |
|
880 Normally, you should always use :func:`~django.core.urlresolvers.reverse` or |
|
881 :func:`~django.db.models.permalink` to define URLs within your application. |
|
882 However, if your application constructs part of the URL hierarchy itself, you |
|
883 may occasionally need to generate URLs. In that case, you need to be able to |
|
884 find the base URL of the Django project within its web server |
|
885 (normally, :func:`~django.core.urlresolvers.reverse` takes care of this for |
|
886 you). In that case, you can call ``get_script_prefix()``, which will return the |
|
887 script prefix portion of the URL for your Django project. If your Django |
|
888 project is at the root of its webserver, this is always ``"/"``, but it can be |
|
889 changed, for instance by using ``django.root`` (see :ref:`How to use |
|
890 Django with Apache and mod_python <howto-deployment-modpython>`). |