urls.txt 32 KB

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