urls.txt 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. .. _topics-http-urls:
  2. ==============
  3. URL dispatcher
  4. ==============
  5. A clean, elegant URL scheme is an important detail in a high-quality Web
  6. application. Django lets you design URLs however you want, with no framework
  7. limitations.
  8. There's no ``.php`` or ``.cgi`` required, and certainly none of that
  9. ``0,2097,1-1-1928,00`` nonsense.
  10. See `Cool URIs don't change`_, by World Wide Web creator Tim Berners-Lee, for
  11. excellent arguments on why URLs should be clean and usable.
  12. .. _Cool URIs don't change: http://www.w3.org/Provider/Style/URI
  13. Overview
  14. ========
  15. To design URLs for an app, you create a Python module informally called a
  16. **URLconf** (URL configuration). This module is pure Python code and
  17. is a simple mapping between URL patterns (as simple regular expressions) to
  18. Python callback functions (your views).
  19. This mapping can be as short or as long as needed. It can reference other
  20. mappings. And, because it's pure Python code, it can be constructed
  21. dynamically.
  22. .. _how-django-processes-a-request:
  23. How Django processes a request
  24. ==============================
  25. When a user requests a page from your Django-powered site, this is the
  26. algorithm the system follows to determine which Python code to execute:
  27. 1. Django determines the root URLconf module to use. Ordinarily,
  28. this is the value of the ``ROOT_URLCONF`` setting, but if the incoming
  29. ``HttpRequest`` object has an attribute called ``urlconf``, its value
  30. will be used in place of the ``ROOT_URLCONF`` setting.
  31. 2. Django loads that Python module and looks for the variable
  32. ``urlpatterns``. This should be a Python list, in the format returned by
  33. the function ``django.conf.urls.defaults.patterns()``.
  34. 3. Django runs through each URL pattern, in order, and stops at the first
  35. one that matches the requested URL.
  36. 4. Once one of the regexes matches, Django imports and calls the given
  37. view, which is a simple Python function. The view gets passed an
  38. :class:`~django.http.HttpRequest` as its first argument and any values
  39. captured in the regex as remaining arguments.
  40. Example
  41. =======
  42. Here's a sample URLconf::
  43. from django.conf.urls.defaults import *
  44. urlpatterns = patterns('',
  45. (r'^articles/2003/$', 'news.views.special_case_2003'),
  46. (r'^articles/(\d{4})/$', 'news.views.year_archive'),
  47. (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
  48. (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
  49. )
  50. Notes:
  51. * ``from django.conf.urls.defaults import *`` makes the ``patterns()``
  52. function available.
  53. * To capture a value from the URL, just put parenthesis around it.
  54. * There's no need to add a leading slash, because every URL has that. For
  55. example, it's ``^articles``, not ``^/articles``.
  56. * The ``'r'`` in front of each regular expression string is optional but
  57. recommended. It tells Python that a string is "raw" -- that nothing in
  58. the string should be escaped. See `Dive Into Python's explanation`_.
  59. Example requests:
  60. * A request to ``/articles/2005/03/`` would match the third entry in the
  61. list. Django would call the function
  62. ``news.views.month_archive(request, '2005', '03')``.
  63. * ``/articles/2005/3/`` would not match any URL patterns, because the
  64. third entry in the list requires two digits for the month.
  65. * ``/articles/2003/`` would match the first pattern in the list, not the
  66. second one, because the patterns are tested in order, and the first one
  67. is the first test to pass. Feel free to exploit the ordering to insert
  68. special cases like this.
  69. * ``/articles/2003`` would not match any of these patterns, because each
  70. pattern requires that the URL end with a slash.
  71. * ``/articles/2003/03/3/`` would match the final pattern. Django would call
  72. the function ``news.views.article_detail(request, '2003', '03', '3')``.
  73. .. _Dive Into Python's explanation: http://diveintopython.org/regular_expressions/street_addresses.html#re.matching.2.3
  74. Named groups
  75. ============
  76. The above example used simple, *non-named* regular-expression groups (via
  77. parenthesis) to capture bits of the URL and pass them as *positional* arguments
  78. to a view. In more advanced usage, it's possible to use *named*
  79. regular-expression groups to capture URL bits and pass them as *keyword*
  80. arguments to a view.
  81. In Python regular expressions, the syntax for named regular-expression groups
  82. is ``(?P<name>pattern)``, where ``name`` is the name of the group and
  83. ``pattern`` is some pattern to match.
  84. Here's the above example URLconf, rewritten to use named groups::
  85. urlpatterns = patterns('',
  86. (r'^articles/2003/$', 'news.views.special_case_2003'),
  87. (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
  88. (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive'),
  89. (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'news.views.article_detail'),
  90. )
  91. This accomplishes exactly the same thing as the previous example, with one
  92. subtle difference: The captured values are passed to view functions as keyword
  93. arguments rather than positional arguments. For example:
  94. * A request to ``/articles/2005/03/`` would call the function
  95. ``news.views.month_archive(request, year='2005', month='03')``, instead
  96. of ``news.views.month_archive(request, '2005', '03')``.
  97. * A request to ``/articles/2003/03/3/`` would call the function
  98. ``news.views.article_detail(request, year='2003', month='03', day='3')``.
  99. In practice, this means your URLconfs are slightly more explicit and less prone
  100. to argument-order bugs -- and you can reorder the arguments in your views'
  101. function definitions. Of course, these benefits come at the cost of brevity;
  102. some developers find the named-group syntax ugly and too verbose.
  103. The matching/grouping algorithm
  104. -------------------------------
  105. Here's the algorithm the URLconf parser follows, with respect to named groups
  106. vs. non-named groups in a regular expression:
  107. If there are any named arguments, it will use those, ignoring non-named arguments.
  108. Otherwise, it will pass all non-named arguments as positional arguments.
  109. In both cases, it will pass any extra keyword arguments as keyword arguments.
  110. See "Passing extra options to view functions" below.
  111. What the URLconf searches against
  112. =================================
  113. The URLconf searches against the requested URL, as a normal Python string. This
  114. does not include GET or POST parameters, or the domain name.
  115. For example, in a request to ``http://www.example.com/myapp/``, the URLconf
  116. will look for ``myapp/``.
  117. In a request to ``http://www.example.com/myapp/?page=3``, the URLconf will look
  118. for ``myapp/``.
  119. The URLconf doesn't look at the request method. In other words, all request
  120. methods -- ``POST``, ``GET``, ``HEAD``, etc. -- will be routed to the same
  121. function for the same URL.
  122. Syntax of the urlpatterns variable
  123. ==================================
  124. ``urlpatterns`` should be a Python list, in the format returned by the function
  125. ``django.conf.urls.defaults.patterns()``. Always use ``patterns()`` to create
  126. the ``urlpatterns`` variable.
  127. Convention is to use ``from django.conf.urls.defaults import *`` at the top of
  128. your URLconf. This gives your module access to these objects:
  129. patterns
  130. --------
  131. A function that takes a prefix, and an arbitrary number of URL patterns, and
  132. returns a list of URL patterns in the format Django needs.
  133. The first argument to ``patterns()`` is a string ``prefix``. See
  134. "The view prefix" below.
  135. The remaining arguments should be tuples in this format::
  136. (regular expression, Python callback function [, optional dictionary [, optional name]])
  137. ...where ``optional dictionary`` and ``optional name`` are optional. (See
  138. `Passing extra options to view functions`_ below.)
  139. .. note::
  140. Because `patterns()` is a function call, it accepts a maximum of 255
  141. arguments (URL patterns, in this case). This is a limit for all Python
  142. function calls. This is rarely a problem in practice, because you'll
  143. typically structure your URL patterns modularly by using `include()`
  144. sections. However, on the off-chance you do hit the 255-argument limit,
  145. realize that `patterns()` returns a Python list, so you can split up the
  146. construction of the list.
  147. ::
  148. urlpatterns = patterns('',
  149. ...
  150. )
  151. urlpatterns += patterns('',
  152. ...
  153. )
  154. Python lists have unlimited size, so there's no limit to how many URL
  155. patterns you can construct. The only limit is that you can only create 254
  156. at a time (the 255th argument is the initial prefix argument).
  157. url
  158. ---
  159. .. versionadded:: 1.0
  160. You can use the ``url()`` function, instead of a tuple, as an argument to
  161. ``patterns()``. This is convenient if you want to specify a name without the
  162. optional extra arguments dictionary. For example::
  163. urlpatterns = patterns('',
  164. url(r'^index/$', index_view, name="main-view"),
  165. ...
  166. )
  167. This function takes five arguments, most of which are optional::
  168. url(regex, view, kwargs=None, name=None, prefix='')
  169. See `Naming URL patterns`_ for why the ``name`` parameter is useful.
  170. The ``prefix`` parameter has the same meaning as the first argument to
  171. ``patterns()`` and is only relevant when you're passing a string as the
  172. ``view`` parameter.
  173. handler404
  174. ----------
  175. A string representing the full Python import path to the view that should be
  176. called if none of the URL patterns match.
  177. By default, this is ``'django.views.defaults.page_not_found'``. That default
  178. value should suffice.
  179. handler500
  180. ----------
  181. A string representing the full Python import path to the view that should be
  182. called in case of server errors. Server errors happen when you have runtime
  183. errors in view code.
  184. By default, this is ``'django.views.defaults.server_error'``. That default
  185. value should suffice.
  186. include
  187. -------
  188. A function that takes a full Python import path to another URLconf that should
  189. be "included" in this place. See `Including other URLconfs`_ below.
  190. Notes on capturing text in URLs
  191. ===============================
  192. Each captured argument is sent to the view as a plain Python string, regardless
  193. of what sort of match the regular expression makes. For example, in this
  194. URLconf line::
  195. (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
  196. ...the ``year`` argument to ``news.views.year_archive()`` will be a string, not
  197. an integer, even though the ``\d{4}`` will only match integer strings.
  198. A convenient trick is to specify default parameters for your views' arguments.
  199. Here's an example URLconf and view::
  200. # URLconf
  201. urlpatterns = patterns('',
  202. (r'^blog/$', 'blog.views.page'),
  203. (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'),
  204. )
  205. # View (in blog/views.py)
  206. def page(request, num="1"):
  207. # Output the appropriate page of blog entries, according to num.
  208. In the above example, both URL patterns point to the same view --
  209. ``blog.views.page`` -- but the first pattern doesn't capture anything from the
  210. URL. If the first pattern matches, the ``page()`` function will use its
  211. default argument for ``num``, ``"1"``. If the second pattern matches,
  212. ``page()`` will use whatever ``num`` value was captured by the regex.
  213. Performance
  214. ===========
  215. Each regular expression in a ``urlpatterns`` is compiled the first time it's
  216. accessed. This makes the system blazingly fast.
  217. The view prefix
  218. ===============
  219. You can specify a common prefix in your ``patterns()`` call, to cut down on
  220. code duplication.
  221. Here's the example URLconf from the :ref:`Django overview <intro-overview>`::
  222. from django.conf.urls.defaults import *
  223. urlpatterns = patterns('',
  224. (r'^articles/(\d{4})/$', 'mysite.news.views.year_archive'),
  225. (r'^articles/(\d{4})/(\d{2})/$', 'mysite.news.views.month_archive'),
  226. (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'mysite.news.views.article_detail'),
  227. )
  228. In this example, each view has a common prefix -- ``'mysite.news.views'``.
  229. Instead of typing that out for each entry in ``urlpatterns``, you can use the
  230. first argument to the ``patterns()`` function to specify a prefix to apply to
  231. each view function.
  232. With this in mind, the above example can be written more concisely as::
  233. from django.conf.urls.defaults import *
  234. urlpatterns = patterns('mysite.news.views',
  235. (r'^articles/(\d{4})/$', 'year_archive'),
  236. (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'),
  237. (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'),
  238. )
  239. Note that you don't put a trailing dot (``"."``) in the prefix. Django puts
  240. that in automatically.
  241. Multiple view prefixes
  242. ----------------------
  243. In practice, you'll probably end up mixing and matching views to the point
  244. where the views in your ``urlpatterns`` won't have a common prefix. However,
  245. you can still take advantage of the view prefix shortcut to remove duplication.
  246. Just add multiple ``patterns()`` objects together, like this:
  247. Old::
  248. from django.conf.urls.defaults import *
  249. urlpatterns = patterns('',
  250. (r'^$', 'django.views.generic.date_based.archive_index'),
  251. (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'django.views.generic.date_based.archive_month'),
  252. (r'^tag/(?P<tag>\w+)/$', 'weblog.views.tag'),
  253. )
  254. New::
  255. from django.conf.urls.defaults import *
  256. urlpatterns = patterns('django.views.generic.date_based',
  257. (r'^$', 'archive_index'),
  258. (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
  259. )
  260. urlpatterns += patterns('weblog.views',
  261. (r'^tag/(?P<tag>\w+)/$', 'tag'),
  262. )
  263. Including other URLconfs
  264. ========================
  265. At any point, your ``urlpatterns`` can "include" other URLconf modules. This
  266. essentially "roots" a set of URLs below other ones.
  267. For example, here's the URLconf for the `Django Web site`_ itself. It includes a
  268. number of other URLconfs::
  269. from django.conf.urls.defaults import *
  270. urlpatterns = patterns('',
  271. (r'^weblog/', include('django_website.apps.blog.urls.blog')),
  272. (r'^documentation/', include('django_website.apps.docs.urls.docs')),
  273. (r'^comments/', include('django.contrib.comments.urls')),
  274. )
  275. Note that the regular expressions in this example don't have a ``$``
  276. (end-of-string match character) but do include a trailing slash. Whenever
  277. Django encounters ``include()``, it chops off whatever part of the URL matched
  278. up to that point and sends the remaining string to the included URLconf for
  279. further processing.
  280. .. _`Django Web site`: http://www.djangoproject.com/
  281. Captured parameters
  282. -------------------
  283. An included URLconf receives any captured parameters from parent URLconfs, so
  284. the following example is valid::
  285. # In settings/urls/main.py
  286. urlpatterns = patterns('',
  287. (r'^(?P<username>\w+)/blog/', include('foo.urls.blog')),
  288. )
  289. # In foo/urls/blog.py
  290. urlpatterns = patterns('foo.views',
  291. (r'^$', 'blog.index'),
  292. (r'^archive/$', 'blog.archive'),
  293. )
  294. In the above example, the captured ``"username"`` variable is passed to the
  295. included URLconf, as expected.
  296. Passing extra options to view functions
  297. =======================================
  298. URLconfs have a hook that lets you pass extra arguments to your view functions,
  299. as a Python dictionary.
  300. Any URLconf tuple can have an optional third element, which should be a
  301. dictionary of extra keyword arguments to pass to the view function.
  302. For example::
  303. urlpatterns = patterns('blog.views',
  304. (r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
  305. )
  306. In this example, for a request to ``/blog/2005/``, Django will call the
  307. ``blog.views.year_archive()`` view, passing it these keyword arguments::
  308. year='2005', foo='bar'
  309. This technique is used in :ref:`generic views <ref-generic-views>` and in the
  310. :ref:`syndication framework <ref-contrib-syndication>` to pass metadata and
  311. options to views.
  312. .. admonition:: Dealing with conflicts
  313. It's possible to have a URL pattern which captures named keyword arguments,
  314. and also passes arguments with the same names in its dictionary of extra
  315. arguments. When this happens, the arguments in the dictionary will be used
  316. instead of the arguments captured in the URL.
  317. Passing extra options to ``include()``
  318. --------------------------------------
  319. Similarly, you can pass extra options to ``include()``. When you pass extra
  320. options to ``include()``, *each* line in the included URLconf will be passed
  321. the extra options.
  322. For example, these two URLconf sets are functionally identical:
  323. Set one::
  324. # main.py
  325. urlpatterns = patterns('',
  326. (r'^blog/', include('inner'), {'blogid': 3}),
  327. )
  328. # inner.py
  329. urlpatterns = patterns('',
  330. (r'^archive/$', 'mysite.views.archive'),
  331. (r'^about/$', 'mysite.views.about'),
  332. )
  333. Set two::
  334. # main.py
  335. urlpatterns = patterns('',
  336. (r'^blog/', include('inner')),
  337. )
  338. # inner.py
  339. urlpatterns = patterns('',
  340. (r'^archive/$', 'mysite.views.archive', {'blogid': 3}),
  341. (r'^about/$', 'mysite.views.about', {'blogid': 3}),
  342. )
  343. Note that extra options will *always* be passed to *every* line in the included
  344. URLconf, regardless of whether the line's view actually accepts those options
  345. as valid. For this reason, this technique is only useful if you're certain that
  346. every view in the included URLconf accepts the extra options you're passing.
  347. Passing callable objects instead of strings
  348. ===========================================
  349. Some developers find it more natural to pass the actual Python function object
  350. rather than a string containing the path to its module. This alternative is
  351. supported -- you can pass any callable object as the view.
  352. For example, given this URLconf in "string" notation::
  353. urlpatterns = patterns('',
  354. (r'^archive/$', 'mysite.views.archive'),
  355. (r'^about/$', 'mysite.views.about'),
  356. (r'^contact/$', 'mysite.views.contact'),
  357. )
  358. You can accomplish the same thing by passing objects rather than strings. Just
  359. be sure to import the objects::
  360. from mysite.views import archive, about, contact
  361. urlpatterns = patterns('',
  362. (r'^archive/$', archive),
  363. (r'^about/$', about),
  364. (r'^contact/$', contact),
  365. )
  366. The following example is functionally identical. It's just a bit more compact
  367. because it imports the module that contains the views, rather than importing
  368. each view individually::
  369. from mysite import views
  370. urlpatterns = patterns('',
  371. (r'^archive/$', views.archive),
  372. (r'^about/$', views.about),
  373. (r'^contact/$', views.contact),
  374. )
  375. The style you use is up to you.
  376. Note that if you use this technique -- passing objects rather than strings --
  377. the view prefix (as explained in "The view prefix" above) will have no effect.
  378. .. _naming-url-patterns:
  379. Naming URL patterns
  380. ===================
  381. .. versionadded:: 1.0
  382. It's fairly common to use the same view function in multiple URL patterns in
  383. your URLconf. For example, these two URL patterns both point to the ``archive``
  384. view::
  385. urlpatterns = patterns('',
  386. (r'^archive/(\d{4})/$', archive),
  387. (r'^archive-summary/(\d{4})/$', archive, {'summary': True}),
  388. )
  389. This is completely valid, but it leads to problems when you try to do reverse
  390. URL matching (through the ``permalink()`` decorator or the :ttag:`url` template
  391. tag. Continuing this example, if you wanted to retrieve the URL for the
  392. ``archive`` view, Django's reverse URL matcher would get confused, because *two*
  393. URLpatterns point at that view.
  394. To solve this problem, Django supports **named URL patterns**. That is, you can
  395. give a name to a URL pattern in order to distinguish it from other patterns
  396. using the same view and parameters. Then, you can use this name in reverse URL
  397. matching.
  398. Here's the above example, rewritten to use named URL patterns::
  399. urlpatterns = patterns('',
  400. url(r'^archive/(\d{4})/$', archive, name="full-archive"),
  401. url(r'^archive-summary/(\d{4})/$', archive, {'summary': True}, "arch-summary"),
  402. )
  403. With these names in place (``full-archive`` and ``arch-summary``), you can
  404. target each pattern individually by using its name:
  405. .. code-block:: html+django
  406. {% url arch-summary 1945 %}
  407. {% url full-archive 2007 %}
  408. Even though both URL patterns refer to the ``archive`` view here, using the
  409. ``name`` parameter to ``url()`` allows you to tell them apart in templates.
  410. The string used for the URL name can contain any characters you like. You are
  411. not restricted to valid Python names.
  412. .. note::
  413. When you name your URL patterns, make sure you use names that are unlikely
  414. to clash with any other application's choice of names. If you call your URL
  415. pattern ``comment``, and another application does the same thing, there's
  416. no guarantee which URL will be inserted into your template when you use
  417. this name.
  418. Putting a prefix on your URL names, perhaps derived from the application
  419. name, will decrease the chances of collision. We recommend something like
  420. ``myapp-comment`` instead of ``comment``.
  421. Utility methods
  422. ===============
  423. reverse()
  424. ---------
  425. If you need to use something similar to the :ttag:`url` template tag in
  426. your code, Django provides the following method (in the
  427. ``django.core.urlresolvers`` module):
  428. .. currentmodule:: django.core.urlresolvers
  429. .. function:: reverse(viewname, urlconf=None, args=None, kwargs=None)
  430. ``viewname`` is either the function name (either a function reference, or the
  431. string version of the name, if you used that form in ``urlpatterns``) or the
  432. `URL pattern name`_. Normally, you won't need to worry about the
  433. ``urlconf`` parameter and will only pass in the positional and keyword
  434. arguments to use in the URL matching. For example::
  435. from django.core.urlresolvers import reverse
  436. def myview(request):
  437. return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
  438. .. _URL pattern name: `Naming URL patterns`_
  439. The ``reverse()`` function can reverse a large variety of regular expression
  440. patterns for URLs, but not every possible one. The main restriction at the
  441. moment is that the pattern cannot contain alternative choices using the
  442. vertical bar (``"|"``) character. You can quite happily use such patterns for
  443. matching against incoming URLs and sending them off to views, but you cannot
  444. reverse such patterns.
  445. .. admonition:: Make sure your views are all correct
  446. As part of working out which URL names map to which patterns, the
  447. ``reverse()`` function has to import all of your URLConf files and examine
  448. the name of each view. This involves importing each view function. If
  449. there are *any* errors whilst importing any of your view functions, it
  450. will cause ``reverse()`` to raise an error, even if that view function is
  451. not the one you are trying to reverse.
  452. Make sure that any views you reference in your URLConf files exist and can
  453. be imported correctly. Do not include lines that reference views you
  454. haven't written yet, because those views will not be importable.
  455. permalink()
  456. -----------
  457. The :func:`django.db.models.permalink` decorator is useful for writing short
  458. methods that return a full URL path. For example, a model's
  459. ``get_absolute_url()`` method. See :func:`django.db.models.permalink` for more.