urls.txt 30 KB

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