urls.txt 30 KB

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