Fixed #8975 -- Added a note to the documentation for reverse() that all views
[django.git] / docs / topics / http / urls.txt
blobdcb434bf398b09feac441d43cad08f9f3a154205
1 .. _topics-http-urls:
3 ==============
4 URL dispatcher
5 ==============
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.
11 There's no ``.php`` or ``.cgi`` required, and certainly none of that
12 ``0,2097,1-1-1928,00`` nonsense.
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.
17 .. _Cool URIs don't change: http://www.w3.org/Provider/Style/URI
19 Overview
20 ========
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).
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.
31 .. _how-django-processes-a-request:
33 How Django processes a request
34 ==============================
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:
39     1. Django determines the root URLconf module to use. Ordinarily,
40        this is the value of the ``ROOT_URLCONF`` setting, but if the incoming
41        ``HttpRequest`` object has an attribute called ``urlconf``, its value
42        will be used in place of the ``ROOT_URLCONF`` setting.
43     
44     2. Django loads that Python module and looks for the variable
45        ``urlpatterns``. This should be a Python list, in the format returned by
46        the function ``django.conf.urls.defaults.patterns()``.
47     
48     3. Django runs through each URL pattern, in order, and stops at the first
49        one that matches the requested URL.
50     
51     4. Once one of the regexes matches, Django imports and calls the given
52        view, which is a simple Python function. The view gets passed an
53        :class:`~django.http.HttpRequest`` as its first argument and any values
54        captured in the regex as remaining arguments.
56 Example
57 =======
59 Here's a sample URLconf::
61     from django.conf.urls.defaults import *
63     urlpatterns = patterns('',
64         (r'^articles/2003/$', 'news.views.special_case_2003'),
65         (r'^articles/(\d{4})/$', 'news.views.year_archive'),
66         (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
67         (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
68     )
70 Notes:
72     * ``from django.conf.urls.defaults import *`` makes the ``patterns()``
73       function available.
75     * To capture a value from the URL, just put parenthesis around it.
77     * There's no need to add a leading slash, because every URL has that. For
78       example, it's ``^articles``, not ``^/articles``.
80     * The ``'r'`` in front of each regular expression string is optional but
81       recommended. It tells Python that a string is "raw" -- that nothing in
82       the string should be escaped. See `Dive Into Python's explanation`_.
84 Example requests:
86     * A request to ``/articles/2005/03/`` would match the third entry in the
87       list. Django would call the function
88       ``news.views.month_archive(request, '2005', '03')``.
90     * ``/articles/2005/3/`` would not match any URL patterns, because the
91       third entry in the list requires two digits for the month.
93     * ``/articles/2003/`` would match the first pattern in the list, not the
94       second one, because the patterns are tested in order, and the first one
95       is the first test to pass. Feel free to exploit the ordering to insert
96       special cases like this.
98     * ``/articles/2003`` would not match any of these patterns, because each
99       pattern requires that the URL end with a slash.
101     * ``/articles/2003/03/3/`` would match the final pattern. Django would call
102       the function ``news.views.article_detail(request, '2003', '03', '3')``.
104 .. _Dive Into Python's explanation: http://diveintopython.org/regular_expressions/street_addresses.html#re.matching.2.3
106 Named groups
107 ============
109 The above example used simple, *non-named* regular-expression groups (via
110 parenthesis) to capture bits of the URL and pass them as *positional* arguments
111 to a view. In more advanced usage, it's possible to use *named*
112 regular-expression groups to capture URL bits and pass them as *keyword*
113 arguments to a view.
115 In Python regular expressions, the syntax for named regular-expression groups
116 is ``(?P<name>pattern)``, where ``name`` is the name of the group and
117 ``pattern`` is some pattern to match.
119 Here's the above example URLconf, rewritten to use named groups::
121     urlpatterns = patterns('',
122         (r'^articles/2003/$', 'news.views.special_case_2003'),
123         (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
124         (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive'),
125         (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'news.views.article_detail'),
126     )
128 This accomplishes exactly the same thing as the previous example, with one
129 subtle difference: The captured values are passed to view functions as keyword
130 arguments rather than positional arguments. For example:
132     * A request to ``/articles/2005/03/`` would call the function
133       ``news.views.month_archive(request, year='2005', month='03')``, instead
134       of ``news.views.month_archive(request, '2005', '03')``.
136     * A request to ``/articles/2003/03/3/`` would call the function
137       ``news.views.article_detail(request, year='2003', month='03', day='3')``.
139 In practice, this means your URLconfs are slightly more explicit and less prone
140 to argument-order bugs -- and you can reorder the arguments in your views'
141 function definitions. Of course, these benefits come at the cost of brevity;
142 some developers find the named-group syntax ugly and too verbose.
144 The matching/grouping algorithm
145 -------------------------------
147 Here's the algorithm the URLconf parser follows, with respect to named groups
148 vs. non-named groups in a regular expression:
150 If there are any named arguments, it will use those, ignoring non-named arguments.
151 Otherwise, it will pass all non-named arguments as positional arguments.
153 In both cases, it will pass any extra keyword arguments as keyword arguments.
154 See "Passing extra options to view functions" below.
156 What the URLconf searches against
157 =================================
159 The URLconf searches against the requested URL, as a normal Python string. This
160 does not include GET or POST parameters, or the domain name.
162 For example, in a request to ``http://www.example.com/myapp/``, the URLconf
163 will look for ``myapp/``.
165 In a request to ``http://www.example.com/myapp/?page=3``, the URLconf will look
166 for ``myapp/``.
168 The URLconf doesn't look at the request method. In other words, all request
169 methods -- ``POST``, ``GET``, ``HEAD``, etc. -- will be routed to the same
170 function for the same URL.
172 Syntax of the urlpatterns variable
173 ==================================
175 ``urlpatterns`` should be a Python list, in the format returned by the function
176 ``django.conf.urls.defaults.patterns()``. Always use ``patterns()`` to create
177 the ``urlpatterns`` variable.
179 Convention is to use ``from django.conf.urls.defaults import *`` at the top of
180 your URLconf. This gives your module access to these objects:
182 patterns
183 --------
185 A function that takes a prefix, and an arbitrary number of URL patterns, and
186 returns a list of URL patterns in the format Django needs.
188 The first argument to ``patterns()`` is a string ``prefix``. See
189 "The view prefix" below.
191 The remaining arguments should be tuples in this format::
193     (regular expression, Python callback function [, optional dictionary [, optional name]])
195 ...where ``optional dictionary`` and ``optional name`` are optional. (See
196 `Passing extra options to view functions`_ below.)
198 .. note::
199     Because `patterns()` is a function call, it accepts a maximum of 255
200     arguments (URL patterns, in this case). This is a limit for all Python
201     function calls. This is rarely a problem in practice, because you'll
202     typically structure your URL patterns modularly by using `include()`
203     sections. However, on the off-chance you do hit the 255-argument limit,
204     realize that `patterns()` returns a Python list, so you can split up the
205     construction of the list.
207     ::
209         urlpatterns = patterns('',
210             ...
211             )
212         urlpatterns += patterns('',
213             ...
214             )
216     Python lists have unlimited size, so there's no limit to how many URL
217     patterns you can construct. The only limit is that you can only create 254
218     at a time (the 255th argument is the initial prefix argument).
223 .. versionadded:: 1.0
225 You can use the ``url()`` function, instead of a tuple, as an argument to
226 ``patterns()``. This is convenient if you want to specify a name without the
227 optional extra arguments dictionary. For example::
229     urlpatterns = patterns('',
230         url(r'/index/$', index_view, name="main-view"),
231         ...
232     )
234 This function takes five arguments, most of which are optional::
236     url(regex, view, kwargs=None, name=None, prefix='')
238 See `Naming URL patterns`_ for why the ``name`` parameter is useful.
240 The ``prefix`` parameter has the same meaning as the first argument to
241 ``patterns()`` and is only relevant when you're passing a string as the
242 ``view`` parameter.
244 handler404
245 ----------
247 A string representing the full Python import path to the view that should be
248 called if none of the URL patterns match.
250 By default, this is ``'django.views.defaults.page_not_found'``. That default
251 value should suffice.
253 handler500
254 ----------
256 A string representing the full Python import path to the view that should be
257 called in case of server errors. Server errors happen when you have runtime
258 errors in view code.
260 By default, this is ``'django.views.defaults.server_error'``. That default
261 value should suffice.
263 include
264 -------
266 A function that takes a full Python import path to another URLconf that should
267 be "included" in this place. See `Including other URLconfs`_ below.
269 Notes on capturing text in URLs
270 ===============================
272 Each captured argument is sent to the view as a plain Python string, regardless
273 of what sort of match the regular expression makes. For example, in this
274 URLconf line::
276     (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
278 ...the ``year`` argument to ``news.views.year_archive()`` will be a string, not
279 an integer, even though the ``\d{4}`` will only match integer strings.
281 A convenient trick is to specify default parameters for your views' arguments.
282 Here's an example URLconf and view::
284     # URLconf
285     urlpatterns = patterns('',
286         (r'^blog/$', 'blog.views.page'),
287         (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'),
288     )
290     # View (in blog/views.py)
291     def page(request, num="1"):
292         # Output the appropriate page of blog entries, according to num.
294 In the above example, both URL patterns point to the same view --
295 ``blog.views.page`` -- but the first pattern doesn't capture anything from the
296 URL. If the first pattern matches, the ``page()`` function will use its
297 default argument for ``num``, ``"1"``. If the second pattern matches,
298 ``page()`` will use whatever ``num`` value was captured by the regex.
300 Performance
301 ===========
303 Each regular expression in a ``urlpatterns`` is compiled the first time it's
304 accessed. This makes the system blazingly fast.
306 The view prefix
307 ===============
309 You can specify a common prefix in your ``patterns()`` call, to cut down on
310 code duplication.
312 Here's the example URLconf from the :ref:`Django overview <intro-overview>`::
314     from django.conf.urls.defaults import *
316     urlpatterns = patterns('',
317         (r'^articles/(\d{4})/$', 'mysite.news.views.year_archive'),
318         (r'^articles/(\d{4})/(\d{2})/$', 'mysite.news.views.month_archive'),
319         (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'mysite.news.views.article_detail'),
320     )
322 In this example, each view has a common prefix -- ``'mysite.news.views'``.
323 Instead of typing that out for each entry in ``urlpatterns``, you can use the
324 first argument to the ``patterns()`` function to specify a prefix to apply to
325 each view function.
327 With this in mind, the above example can be written more concisely as::
329     from django.conf.urls.defaults import *
331     urlpatterns = patterns('mysite.news.views',
332         (r'^articles/(\d{4})/$', 'year_archive'),
333         (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'),
334         (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'),
335     )
337 Note that you don't put a trailing dot (``"."``) in the prefix. Django puts
338 that in automatically.
340 Multiple view prefixes
341 ----------------------
343 In practice, you'll probably end up mixing and matching views to the point
344 where the views in your ``urlpatterns`` won't have a common prefix. However,
345 you can still take advantage of the view prefix shortcut to remove duplication.
346 Just add multiple ``patterns()`` objects together, like this:
348 Old::
350     from django.conf.urls.defaults import *
352     urlpatterns = patterns('',
353         (r'^$', 'django.views.generic.date_based.archive_index'),
354         (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'django.views.generic.date_based.archive_month'),
355         (r'^tag/(?P<tag>\w+)/$', 'weblog.views.tag'),
356     )
358 New::
360     from django.conf.urls.defaults import *
362     urlpatterns = patterns('django.views.generic.date_based',
363         (r'^$', 'archive_index'),
364         (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
365     )
367     urlpatterns += patterns('weblog.views',
368         (r'^tag/(?P<tag>\w+)/$', 'tag'),
369     )
371 Including other URLconfs
372 ========================
374 At any point, your ``urlpatterns`` can "include" other URLconf modules. This
375 essentially "roots" a set of URLs below other ones.
377 For example, here's the URLconf for the `Django Web site`_ itself. It includes a
378 number of other URLconfs::
380     from django.conf.urls.defaults import *
382     urlpatterns = patterns('',
383         (r'^weblog/',        include('django_website.apps.blog.urls.blog')),
384         (r'^documentation/', include('django_website.apps.docs.urls.docs')),
385         (r'^comments/',      include('django.contrib.comments.urls')),
386     )
388 Note that the regular expressions in this example don't have a ``$``
389 (end-of-string match character) but do include a trailing slash. Whenever
390 Django encounters ``include()``, it chops off whatever part of the URL matched
391 up to that point and sends the remaining string to the included URLconf for
392 further processing.
394 .. _`Django Web site`: http://www.djangoproject.com/
396 Captured parameters
397 -------------------
399 An included URLconf receives any captured parameters from parent URLconfs, so
400 the following example is valid::
402     # In settings/urls/main.py
403     urlpatterns = patterns('',
404         (r'^(?P<username>\w+)/blog/', include('foo.urls.blog')),
405     )
407     # In foo/urls/blog.py
408     urlpatterns = patterns('foo.views',
409         (r'^$', 'blog.index'),
410         (r'^archive/$', 'blog.archive'),
411     )
413 In the above example, the captured ``"username"`` variable is passed to the
414 included URLconf, as expected.
416 Passing extra options to view functions
417 =======================================
419 URLconfs have a hook that lets you pass extra arguments to your view functions,
420 as a Python dictionary.
422 Any URLconf tuple can have an optional third element, which should be a
423 dictionary of extra keyword arguments to pass to the view function.
425 For example::
427     urlpatterns = patterns('blog.views',
428         (r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
429     )
431 In this example, for a request to ``/blog/2005/``, Django will call the
432 ``blog.views.year_archive()`` view, passing it these keyword arguments::
434     year='2005', foo='bar'
436 This technique is used in :ref:`generic views <ref-generic-views>` and in the
437 :ref:`syndication framework <ref-contrib-syndication>` to pass metadata and
438 options to views.
440 .. admonition:: Dealing with conflicts
442     It's possible to have a URL pattern which captures named keyword arguments,
443     and also passes arguments with the same names in its dictionary of extra
444     arguments. When this happens, the arguments in the dictionary will be used
445     instead of the arguments captured in the URL.
447 Passing extra options to ``include()``
448 --------------------------------------
450 Similarly, you can pass extra options to ``include()``. When you pass extra
451 options to ``include()``, *each* line in the included URLconf will be passed
452 the extra options.
454 For example, these two URLconf sets are functionally identical:
456 Set one::
458     # main.py
459     urlpatterns = patterns('',
460         (r'^blog/', include('inner'), {'blogid': 3}),
461     )
463     # inner.py
464     urlpatterns = patterns('',
465         (r'^archive/$', 'mysite.views.archive'),
466         (r'^about/$', 'mysite.views.about'),
467     )
469 Set two::
471     # main.py
472     urlpatterns = patterns('',
473         (r'^blog/', include('inner')),
474     )
476     # inner.py
477     urlpatterns = patterns('',
478         (r'^archive/$', 'mysite.views.archive', {'blogid': 3}),
479         (r'^about/$', 'mysite.views.about', {'blogid': 3}),
480     )
482 Note that extra options will *always* be passed to *every* line in the included
483 URLconf, regardless of whether the line's view actually accepts those options
484 as valid. For this reason, this technique is only useful if you're certain that
485 every view in the included URLconf accepts the extra options you're passing.
487 Passing callable objects instead of strings
488 ===========================================
490 Some developers find it more natural to pass the actual Python function object
491 rather than a string containing the path to its module. This alternative is
492 supported -- you can pass any callable object as the view.
494 For example, given this URLconf in "string" notation::
496     urlpatterns = patterns('',
497         (r'^archive/$', 'mysite.views.archive'),
498         (r'^about/$', 'mysite.views.about'),
499         (r'^contact/$', 'mysite.views.contact'),
500     )
502 You can accomplish the same thing by passing objects rather than strings. Just
503 be sure to import the objects::
505     from mysite.views import archive, about, contact
507     urlpatterns = patterns('',
508         (r'^archive/$', archive),
509         (r'^about/$', about),
510         (r'^contact/$', contact),
511     )
513 The following example is functionally identical. It's just a bit more compact
514 because it imports the module that contains the views, rather than importing
515 each view individually::
517     from mysite import views
519     urlpatterns = patterns('',
520         (r'^archive/$', views.archive),
521         (r'^about/$', views.about),
522         (r'^contact/$', views.contact),
523     )
525 The style you use is up to you.
527 Note that if you use this technique -- passing objects rather than strings --
528 the view prefix (as explained in "The view prefix" above) will have no effect.
530 .. _naming-url-patterns:
532 Naming URL patterns
533 ===================
535 .. versionadded:: 1.0
537 It's fairly common to use the same view function in multiple URL patterns in
538 your URLconf. For example, these two URL patterns both point to the ``archive``
539 view::
541     urlpatterns = patterns('',
542         (r'/archive/(\d{4})/$', archive),
543         (r'/archive-summary/(\d{4})/$', archive, {'summary': True}),
544     )
546 This is completely valid, but it leads to problems when you try to do reverse
547 URL matching (through the ``permalink()`` decorator or the :ttag:`url` template
548 tag. Continuing this example, if you wanted to retrieve the URL for the
549 ``archive`` view, Django's reverse URL matcher would get confused, because *two*
550 URLpatterns point at that view.
552 To solve this problem, Django supports **named URL patterns**. That is, you can
553 give a name to a URL pattern in order to distinguish it from other patterns
554 using the same view and parameters. Then, you can use this name in reverse URL
555 matching.
557 Here's the above example, rewritten to used named URL patterns::
559     urlpatterns = patterns('',
560         url(r'/archive/(\d{4})/$', archive, name="full-archive"),
561         url(r'/archive-summary/(\d{4})/$', archive, {'summary': True}, "arch-summary"),
562     )
564 With these names in place (``full-archive`` and ``arch-summary``), you can
565 target each pattern individually by using its name:
567 .. code-block:: html+django
569     {% url arch-summary 1945 %}
570     {% url full-archive 2007 %}
572 Even though both URL patterns refer to the ``archive`` view here, using the
573 ``name`` parameter to ``url()`` allows you to tell them apart in templates.
575 The string used for the URL name can contain any characters you like. You are
576 not restricted to valid Python names.
578 .. note::
580     When you name your URL patterns, make sure you use names that are unlikely
581     to clash with any other application's choice of names. If you call your URL
582     pattern ``comment``, and another application does the same thing, there's
583     no guarantee which URL will be inserted into your template when you use
584     this name.
586     Putting a prefix on your URL names, perhaps derived from the application
587     name, will decrease the chances of collision. We recommend something like
588     ``myapp-comment`` instead of ``comment``.
590 Utility methods
591 ===============
593 reverse()
594 ---------
596 If you need to use something similar to the :ttag:`url` template tag in
597 your code, Django provides the following method (in the
598 ``django.core.urlresolvers`` module):
600 .. currentmodule:: django.core.urlresolvers
601 .. function:: reverse(viewname, urlconf=None, args=None, kwargs=None)
603 ``viewname`` is either the function name (either a function reference, or the
604 string version of the name, if you used that form in ``urlpatterns``) or the
605 `URL pattern name`_.  Normally, you won't need to worry about the
606 ``urlconf`` parameter and will only pass in the positional and keyword
607 arguments to use in the URL matching. For example::
609     from django.core.urlresolvers import reverse
611     def myview(request):
612         return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
614 .. _URL pattern name: `Naming URL patterns`_
616 The ``reverse()`` function can reverse a large variety of regular expression
617 patterns for URLs, but not every possible one. The main restriction at the
618 moment is that the pattern cannot contain alternative choices using the
619 vertical bar (``"|"``) character. You can quite happily use such patterns for
620 matching against incoming URLs and sending them off to views, but you cannot
621 reverse such patterns.
623 .. admonition:: Make sure your views are all correct
625     As part of working out which URL names map to which patterns, the
626     ``reverse()`` function has to import all of your URLConf files and examine
627     the name of each view. This involves importing each view function. If
628     there are *any* errors whilst importing any of your view functions, it
629     will cause ``reverse()`` to raise an error, even if that view function is
630     not the one you are trying to reverse.
632     Make sure that any views you reference in your URLConf files exist and can
633     be imported correctly. Do not include lines that reference views you
634     haven't written yet, because those views will not be importable.
637 permalink()
638 -----------
640 The :func:`django.db.models.permalink` decorator is useful for writing short
641 methods that return a full URL path. For example, a model's
642 ``get_absolute_url()`` method. See :func:`django.db.models.permalink` for more.