urls.txt 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. ==============
  2. URL dispatcher
  3. ==============
  4. .. module:: django.core.urlresolvers
  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. There's no ``.php`` or ``.cgi`` required, and certainly none of that
  9. ``0,2097,1-1-1928,00`` nonsense.
  10. See `Cool URIs don't change`_, by World Wide Web creator Tim Berners-Lee, for
  11. excellent arguments on why URLs should be clean and usable.
  12. .. _Cool URIs don't change: http://www.w3.org/Provider/Style/URI
  13. Overview
  14. ========
  15. To design URLs for an app, you create a Python module informally called a
  16. **URLconf** (URL configuration). This module is pure Python code and
  17. is a simple mapping between URL patterns (as simple regular expressions) to
  18. Python callback functions (your views).
  19. This mapping can be as short or as long as needed. It can reference other
  20. mappings. And, because it's pure Python code, it can be constructed
  21. dynamically.
  22. .. versionadded:: 1.4
  23. Django also allows to translate URLs according to the active language.
  24. This process is described in the
  25. :ref:`internationalization docs <url-internationalization>`.
  26. .. _how-django-processes-a-request:
  27. How Django processes a request
  28. ==============================
  29. When a user requests a page from your Django-powered site, this is the
  30. algorithm the system follows to determine which Python code to execute:
  31. 1. Django determines the root URLconf module to use. Ordinarily,
  32. this is the value of the :setting:`ROOT_URLCONF` setting, but if the incoming
  33. ``HttpRequest`` object has an attribute called ``urlconf`` (set by
  34. middleware :ref:`request processing <request-middleware>`), its value
  35. will be used in place of the :setting:`ROOT_URLCONF` setting.
  36. 2. Django loads that Python module and looks for the variable
  37. ``urlpatterns``. This should be a Python list, in the format returned by
  38. the function :func:`django.conf.urls.patterns`.
  39. 3. Django runs through each URL pattern, in order, and stops at the first
  40. one that matches the requested URL.
  41. 4. Once one of the regexes matches, Django imports and calls the given
  42. view, which is a simple Python function. The view gets passed an
  43. :class:`~django.http.HttpRequest` as its first argument and any values
  44. captured in the regex as remaining arguments.
  45. 5. If no regex matches, or if an exception is raised during any
  46. point in this process, Django invokes an appropriate
  47. error-handling view. See `Error handling`_ below.
  48. Example
  49. =======
  50. Here's a sample URLconf::
  51. from django.conf.urls import patterns, url, include
  52. urlpatterns = patterns('',
  53. (r'^articles/2003/$', 'news.views.special_case_2003'),
  54. (r'^articles/(\d{4})/$', 'news.views.year_archive'),
  55. (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
  56. (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
  57. )
  58. Notes:
  59. * To capture a value from the URL, just put parenthesis around it.
  60. * There's no need to add a leading slash, because every URL has that. For
  61. example, it's ``^articles``, not ``^/articles``.
  62. * The ``'r'`` in front of each regular expression string is optional but
  63. recommended. It tells Python that a string is "raw" -- that nothing in
  64. the string should be escaped. See `Dive Into Python's explanation`_.
  65. Example requests:
  66. * A request to ``/articles/2005/03/`` would match the third entry in the
  67. list. Django would call the function
  68. ``news.views.month_archive(request, '2005', '03')``.
  69. * ``/articles/2005/3/`` would not match any URL patterns, because the
  70. third entry in the list requires two digits for the month.
  71. * ``/articles/2003/`` would match the first pattern in the list, not the
  72. second one, because the patterns are tested in order, and the first one
  73. is the first test to pass. Feel free to exploit the ordering to insert
  74. special cases like this.
  75. * ``/articles/2003`` would not match any of these patterns, because each
  76. pattern requires that the URL end with a slash.
  77. * ``/articles/2003/03/03/`` would match the final pattern. Django would call
  78. the function ``news.views.article_detail(request, '2003', '03', '03')``.
  79. .. _Dive Into Python's explanation: http://diveintopython.net/regular_expressions/street_addresses.html#re.matching.2.3
  80. Named groups
  81. ============
  82. The above example used simple, *non-named* regular-expression groups (via
  83. parenthesis) to capture bits of the URL and pass them as *positional* arguments
  84. to a view. In more advanced usage, it's possible to use *named*
  85. regular-expression groups to capture URL bits and pass them as *keyword*
  86. arguments to a view.
  87. In Python regular expressions, the syntax for named regular-expression groups
  88. is ``(?P<name>pattern)``, where ``name`` is the name of the group and
  89. ``pattern`` is some pattern to match.
  90. Here's the above example URLconf, rewritten to use named groups::
  91. urlpatterns = patterns('',
  92. (r'^articles/2003/$', 'news.views.special_case_2003'),
  93. (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
  94. (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive'),
  95. (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$', 'news.views.article_detail'),
  96. )
  97. This accomplishes exactly the same thing as the previous example, with one
  98. subtle difference: The captured values are passed to view functions as keyword
  99. arguments rather than positional arguments. For example:
  100. * A request to ``/articles/2005/03/`` would call the function
  101. ``news.views.month_archive(request, year='2005', month='03')``, instead
  102. of ``news.views.month_archive(request, '2005', '03')``.
  103. * A request to ``/articles/2003/03/03/`` would call the function
  104. ``news.views.article_detail(request, year='2003', month='03', day='03')``.
  105. In practice, this means your URLconfs are slightly more explicit and less prone
  106. to argument-order bugs -- and you can reorder the arguments in your views'
  107. function definitions. Of course, these benefits come at the cost of brevity;
  108. some developers find the named-group syntax ugly and too verbose.
  109. The matching/grouping algorithm
  110. -------------------------------
  111. Here's the algorithm the URLconf parser follows, with respect to named groups
  112. vs. non-named groups in a regular expression:
  113. If there are any named arguments, it will use those, ignoring non-named arguments.
  114. Otherwise, it will pass all non-named arguments as positional arguments.
  115. In both cases, it will pass any extra keyword arguments as keyword arguments.
  116. See "Passing extra options to view functions" below.
  117. What the URLconf searches against
  118. =================================
  119. The URLconf searches against the requested URL, as a normal Python string. This
  120. does not include GET or POST parameters, or the domain name.
  121. For example, in a request to ``http://www.example.com/myapp/``, the URLconf
  122. will look for ``myapp/``.
  123. In a request to ``http://www.example.com/myapp/?page=3``, the URLconf will look
  124. for ``myapp/``.
  125. The URLconf doesn't look at the request method. In other words, all request
  126. methods -- ``POST``, ``GET``, ``HEAD``, etc. -- will be routed to the same
  127. function for the same URL.
  128. Syntax of the urlpatterns variable
  129. ==================================
  130. ``urlpatterns`` should be a Python list, in the format returned by the function
  131. :func:`django.conf.urls.patterns`. Always use ``patterns()`` to create
  132. the ``urlpatterns`` variable.
  133. ``django.conf.urls`` utility functions
  134. ======================================
  135. .. module:: django.conf.urls
  136. .. deprecated:: 1.4
  137. Starting with Django 1.4 functions ``patterns``, ``url``, ``include`` plus
  138. the ``handler*`` symbols described below live in the ``django.conf.urls``
  139. module.
  140. Until Django 1.3 they were located in ``django.conf.urls.defaults``. You
  141. still can import them from there but it will be removed in Django 1.6.
  142. patterns
  143. --------
  144. .. function:: patterns(prefix, pattern_description, ...)
  145. A function that takes a prefix, and an arbitrary number of URL patterns, and
  146. returns a list of URL patterns in the format Django needs.
  147. The first argument to ``patterns()`` is a string ``prefix``. See
  148. `The view prefix`_ below.
  149. The remaining arguments should be tuples in this format::
  150. (regular expression, Python callback function [, optional dictionary [, optional name]])
  151. ...where ``optional dictionary`` and ``optional name`` are optional. (See
  152. `Passing extra options to view functions`_ below.)
  153. .. note::
  154. Because `patterns()` is a function call, it accepts a maximum of 255
  155. arguments (URL patterns, in this case). This is a limit for all Python
  156. function calls. This is rarely a problem in practice, because you'll
  157. typically structure your URL patterns modularly by using `include()`
  158. sections. However, on the off-chance you do hit the 255-argument limit,
  159. realize that `patterns()` returns a Python list, so you can split up the
  160. construction of the list.
  161. ::
  162. urlpatterns = patterns('',
  163. ...
  164. )
  165. urlpatterns += patterns('',
  166. ...
  167. )
  168. Python lists have unlimited size, so there's no limit to how many URL
  169. patterns you can construct. The only limit is that you can only create 254
  170. at a time (the 255th argument is the initial prefix argument).
  171. url
  172. ---
  173. .. function:: url(regex, view, kwargs=None, name=None, prefix='')
  174. You can use the ``url()`` function, instead of a tuple, as an argument to
  175. ``patterns()``. This is convenient if you want to specify a name without the
  176. optional extra arguments dictionary. For example::
  177. urlpatterns = patterns('',
  178. url(r'^index/$', index_view, name="main-view"),
  179. ...
  180. )
  181. This function takes five arguments, most of which are optional::
  182. url(regex, view, kwargs=None, name=None, prefix='')
  183. See `Naming URL patterns`_ for why the ``name`` parameter is useful.
  184. The ``prefix`` parameter has the same meaning as the first argument to
  185. ``patterns()`` and is only relevant when you're passing a string as the
  186. ``view`` parameter.
  187. include
  188. -------
  189. .. function:: include(<module or pattern_list>)
  190. A function that takes a full Python import path to another URLconf module that
  191. should be "included" in this place.
  192. :func:`include` also accepts as an argument an iterable that returns URL
  193. patterns.
  194. See `Including other URLconfs`_ below.
  195. Error handling
  196. ==============
  197. When Django can't find a regex matching the requested URL, or when an
  198. exception is raised, Django will invoke an error-handling view. The
  199. views to use for these cases are specified by three variables which can
  200. be set in your root URLconf. Setting these variables in any other
  201. URLconf will have no effect.
  202. See the documentation on :ref:`customizing error views
  203. <customizing-error-views>` for more details.
  204. handler403
  205. ----------
  206. .. data:: handler403
  207. A callable, or a string representing the full Python import path to the view
  208. that should be called if the user doesn't have the permissions required to
  209. access a resource.
  210. By default, this is ``'django.views.defaults.permission_denied'``. That default
  211. value should suffice.
  212. See the documentation about :ref:`the 403 (HTTP Forbidden) view
  213. <http_forbidden_view>` for more information.
  214. .. versionadded:: 1.4
  215. ``handler403`` is new in Django 1.4.
  216. handler404
  217. ----------
  218. .. data:: handler404
  219. A callable, or a string representing the full Python import path to the view
  220. that should be called if none of the URL patterns match.
  221. By default, this is ``'django.views.defaults.page_not_found'``. That default
  222. value should suffice.
  223. See the documentation about :ref:`the 404 (HTTP Not Found) view
  224. <http_not_found_view>` for more information.
  225. handler500
  226. ----------
  227. .. data:: handler500
  228. A callable, or a string representing the full Python import path to the view
  229. that should be called in case of server errors. Server errors happen when you
  230. have runtime errors in view code.
  231. By default, this is ``'django.views.defaults.server_error'``. That default
  232. value should suffice.
  233. See the documentation about :ref:`the 500 (HTTP Internal Server Error) view
  234. <http_internal_server_error_view>` for more information.
  235. Notes on capturing text in URLs
  236. ===============================
  237. Each captured argument is sent to the view as a plain Python string, regardless
  238. of what sort of match the regular expression makes. For example, in this
  239. URLconf line::
  240. (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
  241. ...the ``year`` argument to ``news.views.year_archive()`` will be a string, not
  242. an integer, even though the ``\d{4}`` will only match integer strings.
  243. A convenient trick is to specify default parameters for your views' arguments.
  244. Here's an example URLconf and view::
  245. # URLconf
  246. urlpatterns = patterns('',
  247. (r'^blog/$', 'blog.views.page'),
  248. (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'),
  249. )
  250. # View (in blog/views.py)
  251. def page(request, num="1"):
  252. # Output the appropriate page of blog entries, according to num.
  253. In the above example, both URL patterns point to the same view --
  254. ``blog.views.page`` -- but the first pattern doesn't capture anything from the
  255. URL. If the first pattern matches, the ``page()`` function will use its
  256. default argument for ``num``, ``"1"``. If the second pattern matches,
  257. ``page()`` will use whatever ``num`` value was captured by the regex.
  258. Performance
  259. ===========
  260. Each regular expression in a ``urlpatterns`` is compiled the first time it's
  261. accessed. This makes the system blazingly fast.
  262. The view prefix
  263. ===============
  264. You can specify a common prefix in your ``patterns()`` call, to cut down on
  265. code duplication.
  266. Here's the example URLconf from the :doc:`Django overview </intro/overview>`::
  267. from django.conf.urls import patterns, url, include
  268. urlpatterns = patterns('',
  269. (r'^articles/(\d{4})/$', 'news.views.year_archive'),
  270. (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
  271. (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
  272. )
  273. In this example, each view has a common prefix -- ``'news.views'``.
  274. Instead of typing that out for each entry in ``urlpatterns``, you can use the
  275. first argument to the ``patterns()`` function to specify a prefix to apply to
  276. each view function.
  277. With this in mind, the above example can be written more concisely as::
  278. from django.conf.urls import patterns, url, include
  279. urlpatterns = patterns('news.views',
  280. (r'^articles/(\d{4})/$', 'year_archive'),
  281. (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'),
  282. (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'),
  283. )
  284. Note that you don't put a trailing dot (``"."``) in the prefix. Django puts
  285. that in automatically.
  286. Multiple view prefixes
  287. ----------------------
  288. In practice, you'll probably end up mixing and matching views to the point
  289. where the views in your ``urlpatterns`` won't have a common prefix. However,
  290. you can still take advantage of the view prefix shortcut to remove duplication.
  291. Just add multiple ``patterns()`` objects together, like this:
  292. Old::
  293. from django.conf.urls import patterns, url, include
  294. urlpatterns = patterns('',
  295. (r'^$', 'myapp.views.app_index'),
  296. (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'myapp.views.month_display'),
  297. (r'^tag/(?P<tag>\w+)/$', 'weblog.views.tag'),
  298. )
  299. New::
  300. from django.conf.urls import patterns, url, include
  301. urlpatterns = patterns('myapp.views',
  302. (r'^$', 'app_index'),
  303. (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','month_display'),
  304. )
  305. urlpatterns += patterns('weblog.views',
  306. (r'^tag/(?P<tag>\w+)/$', 'tag'),
  307. )
  308. Including other URLconfs
  309. ========================
  310. At any point, your ``urlpatterns`` can "include" other URLconf modules. This
  311. essentially "roots" a set of URLs below other ones.
  312. For example, here's an excerpt of the URLconf for the `Django Web site`_
  313. itself. It includes a number of other URLconfs::
  314. from django.conf.urls import patterns, url, include
  315. urlpatterns = patterns('',
  316. # ... snip ...
  317. (r'^comments/', include('django.contrib.comments.urls')),
  318. (r'^community/', include('django_website.aggregator.urls')),
  319. (r'^contact/', include('django_website.contact.urls')),
  320. (r'^r/', include('django.conf.urls.shortcut')),
  321. # ... snip ...
  322. )
  323. Note that the regular expressions in this example don't have a ``$``
  324. (end-of-string match character) but do include a trailing slash. Whenever
  325. Django encounters ``include()``, it chops off whatever part of the URL matched
  326. up to that point and sends the remaining string to the included URLconf for
  327. further processing.
  328. Another possibility is to include additional URL patterns not by specifying the
  329. URLconf Python module defining them as the `include`_ argument but by using
  330. directly the pattern list as returned by `patterns`_ instead. For example::
  331. from django.conf.urls import patterns, url, include
  332. extra_patterns = patterns('',
  333. url(r'^reports/(?P<id>\d+)/$', 'credit.views.report', name='credit-reports'),
  334. url(r'^charge/$', 'credit.views.charge', name='credit-charge'),
  335. )
  336. urlpatterns = patterns('',
  337. url(r'^$', 'apps.main.views.homepage', name='site-homepage'),
  338. (r'^help/', include('apps.help.urls')),
  339. (r'^credit/', include(extra_patterns)),
  340. )
  341. This approach can be seen in use when you deploy an instance of the Django
  342. Admin application. The Django Admin is deployed as instances of a
  343. :class:`~django.contrib.admin.AdminSite`; each
  344. :class:`~django.contrib.admin.AdminSite` instance has an attribute ``urls``
  345. that returns the url patterns available to that instance. It is this attribute
  346. that you ``include()`` into your projects ``urlpatterns`` when you deploy the
  347. admin instance.
  348. .. _`Django Web site`: https://www.djangoproject.com/
  349. Captured parameters
  350. -------------------
  351. An included URLconf receives any captured parameters from parent URLconfs, so
  352. the following example is valid::
  353. # In settings/urls/main.py
  354. urlpatterns = patterns('',
  355. (r'^(?P<username>\w+)/blog/', include('foo.urls.blog')),
  356. )
  357. # In foo/urls/blog.py
  358. urlpatterns = patterns('foo.views',
  359. (r'^$', 'blog.index'),
  360. (r'^archive/$', 'blog.archive'),
  361. )
  362. In the above example, the captured ``"username"`` variable is passed to the
  363. included URLconf, as expected.
  364. .. _topics-http-defining-url-namespaces:
  365. Defining URL namespaces
  366. -----------------------
  367. When you need to deploy multiple instances of a single application, it can be
  368. helpful to be able to differentiate between instances. This is especially
  369. important when using :ref:`named URL patterns <naming-url-patterns>`, since
  370. multiple instances of a single application will share named URLs. Namespaces
  371. provide a way to tell these named URLs apart.
  372. A URL namespace comes in two parts, both of which are strings:
  373. * An **application namespace**. This describes the name of the application
  374. that is being deployed. Every instance of a single application will have
  375. the same application namespace. For example, Django's admin application
  376. has the somewhat predictable application namespace of ``admin``.
  377. * An **instance namespace**. This identifies a specific instance of an
  378. application. Instance namespaces should be unique across your entire
  379. project. However, an instance namespace can be the same as the
  380. application namespace. This is used to specify a default instance of an
  381. application. For example, the default Django Admin instance has an
  382. instance namespace of ``admin``.
  383. URL Namespaces can be specified in two ways.
  384. Firstly, you can provide the application and instance namespace as arguments
  385. to ``include()`` when you construct your URL patterns. For example,::
  386. (r'^help/', include('apps.help.urls', namespace='foo', app_name='bar')),
  387. This will include the URLs defined in ``apps.help.urls`` into the application
  388. namespace ``bar``, with the instance namespace ``foo``.
  389. Secondly, you can include an object that contains embedded namespace data. If
  390. you ``include()`` a ``patterns`` object, that object will be added to the
  391. global namespace. However, you can also ``include()`` an object that contains
  392. a 3-tuple containing::
  393. (<patterns object>, <application namespace>, <instance namespace>)
  394. This will include the nominated URL patterns into the given application and
  395. instance namespace. For example, the ``urls`` attribute of Django's
  396. :class:`~django.contrib.admin.AdminSite` object returns a 3-tuple that contains
  397. all the patterns in an admin site, plus the name of the admin instance, and the
  398. application namespace ``admin``.
  399. Once you have defined namespaced URLs, you can reverse them. For details on
  400. reversing namespaced urls, see the documentation on :ref:`reversing namespaced
  401. URLs <topics-http-reversing-url-namespaces>`.
  402. Passing extra options to view functions
  403. =======================================
  404. URLconfs have a hook that lets you pass extra arguments to your view functions,
  405. as a Python dictionary.
  406. Any URLconf tuple can have an optional third element, which should be a
  407. dictionary of extra keyword arguments to pass to the view function.
  408. For example::
  409. urlpatterns = patterns('blog.views',
  410. (r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
  411. )
  412. In this example, for a request to ``/blog/2005/``, Django will call the
  413. ``blog.views.year_archive()`` view, passing it these keyword arguments::
  414. year='2005', foo='bar'
  415. This technique is used in the
  416. :doc:`syndication framework </ref/contrib/syndication>` to pass metadata and
  417. options to views.
  418. .. admonition:: Dealing with conflicts
  419. It's possible to have a URL pattern which captures named keyword arguments,
  420. and also passes arguments with the same names in its dictionary of extra
  421. arguments. When this happens, the arguments in the dictionary will be used
  422. instead of the arguments captured in the URL.
  423. Passing extra options to ``include()``
  424. --------------------------------------
  425. Similarly, you can pass extra options to ``include()``. When you pass extra
  426. options to ``include()``, *each* line in the included URLconf will be passed
  427. the extra options.
  428. For example, these two URLconf sets are functionally identical:
  429. Set one::
  430. # main.py
  431. urlpatterns = patterns('',
  432. (r'^blog/', include('inner'), {'blogid': 3}),
  433. )
  434. # inner.py
  435. urlpatterns = patterns('',
  436. (r'^archive/$', 'mysite.views.archive'),
  437. (r'^about/$', 'mysite.views.about'),
  438. )
  439. Set two::
  440. # main.py
  441. urlpatterns = patterns('',
  442. (r'^blog/', include('inner')),
  443. )
  444. # inner.py
  445. urlpatterns = patterns('',
  446. (r'^archive/$', 'mysite.views.archive', {'blogid': 3}),
  447. (r'^about/$', 'mysite.views.about', {'blogid': 3}),
  448. )
  449. Note that extra options will *always* be passed to *every* line in the included
  450. URLconf, regardless of whether the line's view actually accepts those options
  451. as valid. For this reason, this technique is only useful if you're certain that
  452. every view in the included URLconf accepts the extra options you're passing.
  453. Passing callable objects instead of strings
  454. ===========================================
  455. Some developers find it more natural to pass the actual Python function object
  456. rather than a string containing the path to its module. This alternative is
  457. supported -- you can pass any callable object as the view.
  458. For example, given this URLconf in "string" notation::
  459. urlpatterns = patterns('',
  460. (r'^archive/$', 'mysite.views.archive'),
  461. (r'^about/$', 'mysite.views.about'),
  462. (r'^contact/$', 'mysite.views.contact'),
  463. )
  464. You can accomplish the same thing by passing objects rather than strings. Just
  465. be sure to import the objects::
  466. from mysite.views import archive, about, contact
  467. urlpatterns = patterns('',
  468. (r'^archive/$', archive),
  469. (r'^about/$', about),
  470. (r'^contact/$', contact),
  471. )
  472. The following example is functionally identical. It's just a bit more compact
  473. because it imports the module that contains the views, rather than importing
  474. each view individually::
  475. from mysite import views
  476. urlpatterns = patterns('',
  477. (r'^archive/$', views.archive),
  478. (r'^about/$', views.about),
  479. (r'^contact/$', views.contact),
  480. )
  481. The style you use is up to you.
  482. Note that if you use this technique -- passing objects rather than strings --
  483. the view prefix (as explained in "The view prefix" above) will have no effect.
  484. .. _naming-url-patterns:
  485. Naming URL patterns
  486. ===================
  487. It's fairly common to use the same view function in multiple URL patterns in
  488. your URLconf. For example, these two URL patterns both point to the ``archive``
  489. view::
  490. urlpatterns = patterns('',
  491. (r'^archive/(\d{4})/$', archive),
  492. (r'^archive-summary/(\d{4})/$', archive, {'summary': True}),
  493. )
  494. This is completely valid, but it leads to problems when you try to do reverse
  495. URL matching (through the ``permalink()`` decorator or the :ttag:`url` template
  496. tag). Continuing this example, if you wanted to retrieve the URL for the
  497. ``archive`` view, Django's reverse URL matcher would get confused, because *two*
  498. URL patterns point at that view.
  499. To solve this problem, Django supports **named URL patterns**. That is, you can
  500. give a name to a URL pattern in order to distinguish it from other patterns
  501. using the same view and parameters. Then, you can use this name in reverse URL
  502. matching.
  503. Here's the above example, rewritten to use named URL patterns::
  504. urlpatterns = patterns('',
  505. url(r'^archive/(\d{4})/$', archive, name="full-archive"),
  506. url(r'^archive-summary/(\d{4})/$', archive, {'summary': True}, "arch-summary"),
  507. )
  508. With these names in place (``full-archive`` and ``arch-summary``), you can
  509. target each pattern individually by using its name:
  510. .. code-block:: html+django
  511. {% url 'arch-summary' 1945 %}
  512. {% url 'full-archive' 2007 %}
  513. Even though both URL patterns refer to the ``archive`` view here, using the
  514. ``name`` parameter to ``url()`` allows you to tell them apart in templates.
  515. The string used for the URL name can contain any characters you like. You are
  516. not restricted to valid Python names.
  517. .. note::
  518. When you name your URL patterns, make sure you use names that are unlikely
  519. to clash with any other application's choice of names. If you call your URL
  520. pattern ``comment``, and another application does the same thing, there's
  521. no guarantee which URL will be inserted into your template when you use
  522. this name.
  523. Putting a prefix on your URL names, perhaps derived from the application
  524. name, will decrease the chances of collision. We recommend something like
  525. ``myapp-comment`` instead of ``comment``.
  526. .. _topics-http-reversing-url-namespaces:
  527. URL namespaces
  528. --------------
  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 ``foo:bar:whiz`` would look for
  533. a pattern named ``whiz`` in the namespace ``bar`` that is itself defined within
  534. the top-level namespace ``foo``.
  535. When given a namespaced URL (e.g. ``myapp:index``) to resolve, Django splits
  536. the fully qualified name into parts, and then tries the following lookup:
  537. 1. First, Django looks for a matching application namespace (in this
  538. example, ``myapp``). This will yield a list of instances of that
  539. application.
  540. 2. If there is a *current* application defined, Django finds and returns
  541. the URL resolver for that instance. The *current* application can be
  542. specified as an attribute on the template context - applications that
  543. expect to have multiple deployments should set the ``current_app``
  544. attribute on any ``Context`` or ``RequestContext`` that is used to
  545. render a template.
  546. The current application can also be specified manually as an argument
  547. to the :func:`reverse()` function.
  548. 3. If there is no current application. Django looks for a default
  549. application instance. The default application instance is the instance
  550. that has an instance namespace matching the application namespace (in
  551. this example, an instance of the ``myapp`` called ``myapp``).
  552. 4. If there is no default application instance, Django will pick the last
  553. deployed instance of the application, whatever its instance name may be.
  554. 5. If the provided namespace doesn't match an application namespace in
  555. step 1, Django will attempt a direct lookup of the namespace as an
  556. instance namespace.
  557. If there are nested namespaces, these steps are repeated for each part of the
  558. namespace until only the view name is unresolved. The view name will then be
  559. resolved into a URL in the namespace that has been found.
  560. To show this resolution strategy in action, consider an example of two instances
  561. of ``myapp``: one called ``foo``, and one called ``bar``. ``myapp`` has a main
  562. index page with a URL named `index`. Using this setup, the following lookups are
  563. possible:
  564. * If one of the instances is current - say, if we were rendering a utility page
  565. in the instance ``bar`` - ``myapp:index`` will resolve to the index page of
  566. the instance ``bar``.
  567. * If there is no current instance - say, if we were rendering a page
  568. somewhere else on the site - ``myapp:index`` will resolve to the last
  569. registered instance of ``myapp``. Since there is no default instance,
  570. the last instance of ``myapp`` that is registered will be used. This could
  571. be ``foo`` or ``bar``, depending on the order they are introduced into the
  572. urlpatterns of the project.
  573. * ``foo:index`` will always resolve to the index page of the instance ``foo``.
  574. If there was also a default instance - i.e., an instance named `myapp` - the
  575. following would happen:
  576. * If one of the instances is current - say, if we were rendering a utility page
  577. in the instance ``bar`` - ``myapp:index`` will resolve to the index page of
  578. the instance ``bar``.
  579. * If there is no current instance - say, if we were rendering a page somewhere
  580. else on the site - ``myapp:index`` will resolve to the index page of the
  581. default instance.
  582. * ``foo:index`` will again resolve to the index page of the instance ``foo``.
  583. ``django.core.urlresolvers`` utility functions
  584. ==============================================
  585. .. currentmodule:: django.core.urlresolvers
  586. reverse()
  587. ---------
  588. If you need to use something similar to the :ttag:`url` template tag in
  589. your code, Django provides the following function (in the
  590. :mod:`django.core.urlresolvers` module):
  591. .. function:: reverse(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
  592. ``viewname`` is either the function name (either a function reference, or the
  593. string version of the name, if you used that form in ``urlpatterns``) or the
  594. `URL pattern name`_. Normally, you won't need to worry about the
  595. ``urlconf`` parameter and will only pass in the positional and keyword
  596. arguments to use in the URL matching. For example::
  597. from django.core.urlresolvers import reverse
  598. def myview(request):
  599. return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
  600. .. _URL pattern name: `Naming URL patterns`_
  601. The ``reverse()`` function can reverse a large variety of regular expression
  602. patterns for URLs, but not every possible one. The main restriction at the
  603. moment is that the pattern cannot contain alternative choices using the
  604. vertical bar (``"|"``) character. You can quite happily use such patterns for
  605. matching against incoming URLs and sending them off to views, but you cannot
  606. reverse such patterns.
  607. The ``current_app`` argument allows you to provide a hint to the resolver
  608. indicating the application to which the currently executing view belongs.
  609. This ``current_app`` argument is used as a hint to resolve application
  610. namespaces into URLs on specific application instances, according to the
  611. :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
  612. You can use ``kwargs`` instead of ``args``. For example::
  613. >>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
  614. '/admin/auth/'
  615. ``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.
  616. .. admonition:: Make sure your views are all correct.
  617. As part of working out which URL names map to which patterns, the
  618. ``reverse()`` function has to import all of your URLconf files and examine
  619. the name of each view. This involves importing each view function. If
  620. there are *any* errors whilst importing any of your view functions, it
  621. will cause ``reverse()`` to raise an error, even if that view function is
  622. not the one you are trying to reverse.
  623. Make sure that any views you reference in your URLconf files exist and can
  624. be imported correctly. Do not include lines that reference views you
  625. haven't written yet, because those views will not be importable.
  626. .. note::
  627. The string returned by :meth:`~django.core.urlresolvers.reverse` is already
  628. :ref:`urlquoted <uri-and-iri-handling>`. For example::
  629. >>> reverse('cities', args=[u'Orléans'])
  630. '.../Orl%C3%A9ans/'
  631. Applying further encoding (such as :meth:`~django.utils.http.urlquote` or
  632. ``urllib.quote``) to the output of :meth:`~django.core.urlresolvers.reverse`
  633. may produce undesirable results.
  634. reverse_lazy()
  635. --------------
  636. .. versionadded:: 1.4
  637. A lazily evaluated version of `reverse()`_.
  638. .. function:: reverse_lazy(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
  639. It is useful for when you need to use a URL reversal before your project's
  640. URLConf is loaded. Some common cases where this function is necessary are:
  641. * providing a reversed URL as the ``url`` attribute of a generic class-based
  642. view.
  643. * providing a reversed URL to a decorator (such as the ``login_url`` argument
  644. for the :func:`django.contrib.auth.decorators.permission_required`
  645. decorator).
  646. * providing a reversed URL as a default value for a parameter in a function's
  647. signature.
  648. resolve()
  649. ---------
  650. The :func:`django.core.urlresolvers.resolve` function can be used for
  651. resolving URL paths to the corresponding view functions. It has the
  652. following signature:
  653. .. function:: resolve(path, urlconf=None)
  654. ``path`` is the URL path you want to resolve. As with
  655. :func:`~django.core.urlresolvers.reverse`, you don't need to
  656. worry about the ``urlconf`` parameter. The function returns a
  657. :class:`ResolverMatch` object that allows you
  658. to access various meta-data about the resolved URL.
  659. If the URL does not resolve, the function raises an
  660. :class:`~django.http.Http404` exception.
  661. .. class:: ResolverMatch
  662. .. attribute:: ResolverMatch.func
  663. The view function that would be used to serve the URL
  664. .. attribute:: ResolverMatch.args
  665. The arguments that would be passed to the view function, as
  666. parsed from the URL.
  667. .. attribute:: ResolverMatch.kwargs
  668. The keyword arguments that would be passed to the view
  669. function, as parsed from the URL.
  670. .. attribute:: ResolverMatch.url_name
  671. The name of the URL pattern that matches the URL.
  672. .. attribute:: ResolverMatch.app_name
  673. The application namespace for the URL pattern that matches the
  674. URL.
  675. .. attribute:: ResolverMatch.namespace
  676. The instance namespace for the URL pattern that matches the
  677. URL.
  678. .. attribute:: ResolverMatch.namespaces
  679. The list of individual namespace components in the full
  680. instance namespace for the URL pattern that matches the URL.
  681. i.e., if the namespace is ``foo:bar``, then namespaces will be
  682. ``['foo', 'bar']``.
  683. A :class:`ResolverMatch` object can then be interrogated to provide
  684. information about the URL pattern that matches a URL::
  685. # Resolve a URL
  686. match = resolve('/some/path/')
  687. # Print the URL pattern that matches the URL
  688. print(match.url_name)
  689. A :class:`ResolverMatch` object can also be assigned to a triple::
  690. func, args, kwargs = resolve('/some/path/')
  691. .. versionchanged:: 1.3
  692. Triple-assignment exists for backwards-compatibility. Prior to
  693. Django 1.3, :func:`~django.core.urlresolvers.resolve` returned a
  694. triple containing (view function, arguments, keyword arguments);
  695. the :class:`ResolverMatch` object (as well as the namespace and pattern
  696. information it provides) is not available in earlier Django releases.
  697. One possible use of :func:`~django.core.urlresolvers.resolve` would be to test
  698. whether a view would raise a ``Http404`` error before redirecting to it::
  699. from urlparse import urlparse
  700. from django.core.urlresolvers import resolve
  701. from django.http import HttpResponseRedirect, Http404
  702. def myview(request):
  703. next = request.META.get('HTTP_REFERER', None) or '/'
  704. response = HttpResponseRedirect(next)
  705. # modify the request and response as required, e.g. change locale
  706. # and set corresponding locale cookie
  707. view, args, kwargs = resolve(urlparse(next)[2])
  708. kwargs['request'] = request
  709. try:
  710. view(*args, **kwargs)
  711. except Http404:
  712. return HttpResponseRedirect('/')
  713. return response
  714. permalink()
  715. -----------
  716. The :func:`django.db.models.permalink` decorator is useful for writing short
  717. methods that return a full URL path. For example, a model's
  718. ``get_absolute_url()`` method. See :func:`django.db.models.permalink` for more.
  719. get_script_prefix()
  720. -------------------
  721. .. function:: get_script_prefix()
  722. Normally, you should always use :func:`~django.core.urlresolvers.reverse` or
  723. :func:`~django.db.models.permalink` to define URLs within your application.
  724. However, if your application constructs part of the URL hierarchy itself, you
  725. may occasionally need to generate URLs. In that case, you need to be able to
  726. find the base URL of the Django project within its Web server
  727. (normally, :func:`~django.core.urlresolvers.reverse` takes care of this for
  728. you). In that case, you can call ``get_script_prefix()``, which will return the
  729. script prefix portion of the URL for your Django project. If your Django
  730. project is at the root of its Web server, this is always ``"/"``.