urls.txt 35 KB

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