urls.txt 32 KB

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