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