urls.txt 31 KB

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