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