urls.txt 26 KB

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