2
0

urls.txt 33 KB

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