urls.txt 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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.org/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 two 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 has no the permissions required to access
  209. 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. .. versionchanged:: 1.2
  224. Previous versions of Django only accepted strings representing import paths.
  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. .. versionchanged:: 1.2
  234. Previous versions of Django only accepted strings representing import paths.
  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'^$', 'django.views.generic.date_based.archive_index'),
  296. (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'django.views.generic.date_based.archive_month'),
  297. (r'^tag/(?P<tag>\w+)/$', 'weblog.views.tag'),
  298. )
  299. New::
  300. from django.conf.urls import patterns, url, include
  301. urlpatterns = patterns('django.views.generic.date_based',
  302. (r'^$', 'archive_index'),
  303. (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
  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 the URLconf for the `Django Web site`_ itself. It includes a
  313. number of other URLconfs::
  314. from django.conf.urls import patterns, url, include
  315. urlpatterns = patterns('',
  316. (r'^weblog/', include('django_website.apps.blog.urls.blog')),
  317. (r'^documentation/', include('django_website.apps.docs.urls.docs')),
  318. (r'^comments/', include('django.contrib.comments.urls')),
  319. )
  320. Note that the regular expressions in this example don't have a ``$``
  321. (end-of-string match character) but do include a trailing slash. Whenever
  322. Django encounters ``include()``, it chops off whatever part of the URL matched
  323. up to that point and sends the remaining string to the included URLconf for
  324. further processing.
  325. Another possibility is to include additional URL patterns not by specifying the
  326. URLconf Python module defining them as the `include`_ argument but by using
  327. directly the pattern list as returned by `patterns`_ instead. For example::
  328. from django.conf.urls import patterns, url, include
  329. extra_patterns = patterns('',
  330. url(r'reports/(?P<id>\d+)/$', 'credit.views.report', name='credit-reports'),
  331. url(r'charge/$', 'credit.views.charge', name='credit-charge'),
  332. )
  333. urlpatterns = patterns('',
  334. url(r'^$', 'apps.main.views.homepage', name='site-homepage'),
  335. (r'^help/', include('apps.help.urls')),
  336. (r'^credit/', include(extra_patterns)),
  337. )
  338. This approach can be seen in use when you deploy an instance of the Django
  339. Admin application. The Django Admin is deployed as instances of a
  340. :class:`~django.contrib.admin.AdminSite`; each
  341. :class:`~django.contrib.admin.AdminSite` instance has an attribute ``urls``
  342. that returns the url patterns available to that instance. It is this attribute
  343. that you ``include()`` into your projects ``urlpatterns`` when you deploy the
  344. admin instance.
  345. .. _`Django Web site`: http://www.djangoproject.com/
  346. Captured parameters
  347. -------------------
  348. An included URLconf receives any captured parameters from parent URLconfs, so
  349. the following example is valid::
  350. # In settings/urls/main.py
  351. urlpatterns = patterns('',
  352. (r'^(?P<username>\w+)/blog/', include('foo.urls.blog')),
  353. )
  354. # In foo/urls/blog.py
  355. urlpatterns = patterns('foo.views',
  356. (r'^$', 'blog.index'),
  357. (r'^archive/$', 'blog.archive'),
  358. )
  359. In the above example, the captured ``"username"`` variable is passed to the
  360. included URLconf, as expected.
  361. .. _topics-http-defining-url-namespaces:
  362. Defining URL namespaces
  363. -----------------------
  364. When you need to deploy multiple instances of a single application, it can be
  365. helpful to be able to differentiate between instances. This is especially
  366. important when using :ref:`named URL patterns <naming-url-patterns>`, since
  367. multiple instances of a single application will share named URLs. Namespaces
  368. provide a way to tell these named URLs apart.
  369. A URL namespace comes in two parts, both of which are strings:
  370. * An **application namespace**. This describes the name of the application
  371. that is being deployed. Every instance of a single application will have
  372. the same application namespace. For example, Django's admin application
  373. has the somewhat predictable application namespace of ``admin``.
  374. * An **instance namespace**. This identifies a specific instance of an
  375. application. Instance namespaces should be unique across your entire
  376. project. However, an instance namespace can be the same as the
  377. application namespace. This is used to specify a default instance of an
  378. application. For example, the default Django Admin instance has an
  379. instance namespace of ``admin``.
  380. URL Namespaces can be specified in two ways.
  381. Firstly, you can provide the application and instance namespace as arguments
  382. to ``include()`` when you construct your URL patterns. For example,::
  383. (r'^help/', include('apps.help.urls', namespace='foo', app_name='bar')),
  384. This will include the URLs defined in ``apps.help.urls`` into the application
  385. namespace ``bar``, with the instance namespace ``foo``.
  386. Secondly, you can include an object that contains embedded namespace data. If
  387. you ``include()`` a ``patterns`` object, that object will be added to the
  388. global namespace. However, you can also ``include()`` an object that contains
  389. a 3-tuple containing::
  390. (<patterns object>, <application namespace>, <instance namespace>)
  391. This will include the nominated URL patterns into the given application and
  392. instance namespace. For example, the ``urls`` attribute of Django's
  393. :class:`~django.contrib.admin.AdminSite` object returns a 3-tuple that contains
  394. all the patterns in an admin site, plus the name of the admin instance, and the
  395. application namespace ``admin``.
  396. Once you have defined namespaced URLs, you can reverse them. For details on
  397. reversing namespaced urls, see the documentation on :ref:`reversing namespaced
  398. URLs <topics-http-reversing-url-namespaces>`.
  399. Passing extra options to view functions
  400. =======================================
  401. URLconfs have a hook that lets you pass extra arguments to your view functions,
  402. as a Python dictionary.
  403. Any URLconf tuple can have an optional third element, which should be a
  404. dictionary of extra keyword arguments to pass to the view function.
  405. For example::
  406. urlpatterns = patterns('blog.views',
  407. (r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
  408. )
  409. In this example, for a request to ``/blog/2005/``, Django will call the
  410. ``blog.views.year_archive()`` view, passing it these keyword arguments::
  411. year='2005', foo='bar'
  412. This technique is used in :doc:`generic views </ref/generic-views>` and in the
  413. :doc:`syndication framework </ref/contrib/syndication>` to pass metadata and
  414. options to views.
  415. .. admonition:: Dealing with conflicts
  416. It's possible to have a URL pattern which captures named keyword arguments,
  417. and also passes arguments with the same names in its dictionary of extra
  418. arguments. When this happens, the arguments in the dictionary will be used
  419. instead of the arguments captured in the URL.
  420. Passing extra options to ``include()``
  421. --------------------------------------
  422. Similarly, you can pass extra options to ``include()``. When you pass extra
  423. options to ``include()``, *each* line in the included URLconf will be passed
  424. the extra options.
  425. For example, these two URLconf sets are functionally identical:
  426. Set one::
  427. # main.py
  428. urlpatterns = patterns('',
  429. (r'^blog/', include('inner'), {'blogid': 3}),
  430. )
  431. # inner.py
  432. urlpatterns = patterns('',
  433. (r'^archive/$', 'mysite.views.archive'),
  434. (r'^about/$', 'mysite.views.about'),
  435. )
  436. Set two::
  437. # main.py
  438. urlpatterns = patterns('',
  439. (r'^blog/', include('inner')),
  440. )
  441. # inner.py
  442. urlpatterns = patterns('',
  443. (r'^archive/$', 'mysite.views.archive', {'blogid': 3}),
  444. (r'^about/$', 'mysite.views.about', {'blogid': 3}),
  445. )
  446. Note that extra options will *always* be passed to *every* line in the included
  447. URLconf, regardless of whether the line's view actually accepts those options
  448. as valid. For this reason, this technique is only useful if you're certain that
  449. every view in the included URLconf accepts the extra options you're passing.
  450. Passing callable objects instead of strings
  451. ===========================================
  452. Some developers find it more natural to pass the actual Python function object
  453. rather than a string containing the path to its module. This alternative is
  454. supported -- you can pass any callable object as the view.
  455. For example, given this URLconf in "string" notation::
  456. urlpatterns = patterns('',
  457. (r'^archive/$', 'mysite.views.archive'),
  458. (r'^about/$', 'mysite.views.about'),
  459. (r'^contact/$', 'mysite.views.contact'),
  460. )
  461. You can accomplish the same thing by passing objects rather than strings. Just
  462. be sure to import the objects::
  463. from mysite.views import archive, about, contact
  464. urlpatterns = patterns('',
  465. (r'^archive/$', archive),
  466. (r'^about/$', about),
  467. (r'^contact/$', contact),
  468. )
  469. The following example is functionally identical. It's just a bit more compact
  470. because it imports the module that contains the views, rather than importing
  471. each view individually::
  472. from mysite import views
  473. urlpatterns = patterns('',
  474. (r'^archive/$', views.archive),
  475. (r'^about/$', views.about),
  476. (r'^contact/$', views.contact),
  477. )
  478. The style you use is up to you.
  479. Note that if you use this technique -- passing objects rather than strings --
  480. the view prefix (as explained in "The view prefix" above) will have no effect.
  481. .. _naming-url-patterns:
  482. Naming URL patterns
  483. ===================
  484. It's fairly common to use the same view function in multiple URL patterns in
  485. your URLconf. For example, these two URL patterns both point to the ``archive``
  486. view::
  487. urlpatterns = patterns('',
  488. (r'^archive/(\d{4})/$', archive),
  489. (r'^archive-summary/(\d{4})/$', archive, {'summary': True}),
  490. )
  491. This is completely valid, but it leads to problems when you try to do reverse
  492. URL matching (through the ``permalink()`` decorator or the :ttag:`url` template
  493. tag). Continuing this example, if you wanted to retrieve the URL for the
  494. ``archive`` view, Django's reverse URL matcher would get confused, because *two*
  495. URLpatterns point at that view.
  496. To solve this problem, Django supports **named URL patterns**. That is, you can
  497. give a name to a URL pattern in order to distinguish it from other patterns
  498. using the same view and parameters. Then, you can use this name in reverse URL
  499. matching.
  500. Here's the above example, rewritten to use named URL patterns::
  501. urlpatterns = patterns('',
  502. url(r'^archive/(\d{4})/$', archive, name="full-archive"),
  503. url(r'^archive-summary/(\d{4})/$', archive, {'summary': True}, "arch-summary"),
  504. )
  505. With these names in place (``full-archive`` and ``arch-summary``), you can
  506. target each pattern individually by using its name:
  507. .. code-block:: html+django
  508. {% url arch-summary 1945 %}
  509. {% url full-archive 2007 %}
  510. Even though both URL patterns refer to the ``archive`` view here, using the
  511. ``name`` parameter to ``url()`` allows you to tell them apart in templates.
  512. The string used for the URL name can contain any characters you like. You are
  513. not restricted to valid Python names.
  514. .. note::
  515. When you name your URL patterns, make sure you use names that are unlikely
  516. to clash with any other application's choice of names. If you call your URL
  517. pattern ``comment``, and another application does the same thing, there's
  518. no guarantee which URL will be inserted into your template when you use
  519. this name.
  520. Putting a prefix on your URL names, perhaps derived from the application
  521. name, will decrease the chances of collision. We recommend something like
  522. ``myapp-comment`` instead of ``comment``.
  523. .. _topics-http-reversing-url-namespaces:
  524. URL namespaces
  525. --------------
  526. Namespaced URLs are specified using the ``:`` operator. For example, the main
  527. index page of the admin application is referenced using ``admin:index``. This
  528. indicates a namespace of ``admin``, and a named URL of ``index``.
  529. Namespaces can also be nested. The named URL ``foo:bar:whiz`` would look for
  530. a pattern named ``whiz`` in the namespace ``bar`` that is itself defined within
  531. the top-level namespace ``foo``.
  532. When given a namespaced URL (e.g. ``myapp:index``) to resolve, Django splits
  533. the fully qualified name into parts, and then tries the following lookup:
  534. 1. First, Django looks for a matching application namespace (in this
  535. example, ``myapp``). This will yield a list of instances of that
  536. application.
  537. 2. If there is a *current* application defined, Django finds and returns
  538. the URL resolver for that instance. The *current* application can be
  539. specified as an attribute on the template context - applications that
  540. expect to have multiple deployments should set the ``current_app``
  541. attribute on any ``Context`` or ``RequestContext`` that is used to
  542. render a template.
  543. The current application can also be specified manually as an argument
  544. to the :func:`reverse()` function.
  545. 3. If there is no current application. Django looks for a default
  546. application instance. The default application instance is the instance
  547. that has an instance namespace matching the application namespace (in
  548. this example, an instance of the ``myapp`` called ``myapp``).
  549. 4. If there is no default application instance, Django will pick the last
  550. deployed instance of the application, whatever its instance name may be.
  551. 5. If the provided namespace doesn't match an application namespace in
  552. step 1, Django will attempt a direct lookup of the namespace as an
  553. instance namespace.
  554. If there are nested namespaces, these steps are repeated for each part of the
  555. namespace until only the view name is unresolved. The view name will then be
  556. resolved into a URL in the namespace that has been found.
  557. To show this resolution strategy in action, consider an example of two instances
  558. of ``myapp``: one called ``foo``, and one called ``bar``. ``myapp`` has a main
  559. index page with a URL named `index`. Using this setup, the following lookups are
  560. possible:
  561. * If one of the instances is current - say, if we were rendering a utility page
  562. in the instance ``bar`` - ``myapp:index`` will resolve to the index page of
  563. the instance ``bar``.
  564. * If there is no current instance - say, if we were rendering a page
  565. somewhere else on the site - ``myapp:index`` will resolve to the last
  566. registered instance of ``myapp``. Since there is no default instance,
  567. the last instance of ``myapp`` that is registered will be used. This could
  568. be ``foo`` or ``bar``, depending on the order they are introduced into the
  569. urlpatterns of the project.
  570. * ``foo:index`` will always resolve to the index page of the instance ``foo``.
  571. If there was also a default instance - i.e., an instance named `myapp` - the
  572. following would happen:
  573. * If one of the instances is current - say, if we were rendering a utility page
  574. in the instance ``bar`` - ``myapp:index`` will resolve to the index page of
  575. the instance ``bar``.
  576. * If there is no current instance - say, if we were rendering a page somewhere
  577. else on the site - ``myapp:index`` will resolve to the index page of the
  578. default instance.
  579. * ``foo:index`` will again resolve to the index page of the instance ``foo``.
  580. ``django.core.urlresolvers`` utility functions
  581. ==============================================
  582. .. currentmodule:: django.core.urlresolvers
  583. reverse()
  584. ---------
  585. If you need to use something similar to the :ttag:`url` template tag in
  586. your code, Django provides the following function (in the
  587. :mod:`django.core.urlresolvers` module):
  588. .. function:: reverse(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
  589. ``viewname`` is either the function name (either a function reference, or the
  590. string version of the name, if you used that form in ``urlpatterns``) or the
  591. `URL pattern name`_. Normally, you won't need to worry about the
  592. ``urlconf`` parameter and will only pass in the positional and keyword
  593. arguments to use in the URL matching. For example::
  594. from django.core.urlresolvers import reverse
  595. def myview(request):
  596. return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
  597. .. _URL pattern name: `Naming URL patterns`_
  598. The ``reverse()`` function can reverse a large variety of regular expression
  599. patterns for URLs, but not every possible one. The main restriction at the
  600. moment is that the pattern cannot contain alternative choices using the
  601. vertical bar (``"|"``) character. You can quite happily use such patterns for
  602. matching against incoming URLs and sending them off to views, but you cannot
  603. reverse such patterns.
  604. The ``current_app`` argument allows you to provide a hint to the resolver
  605. indicating the application to which the currently executing view belongs.
  606. This ``current_app`` argument is used as a hint to resolve application
  607. namespaces into URLs on specific application instances, according to the
  608. :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
  609. ``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.
  610. .. admonition:: Make sure your views are all correct.
  611. As part of working out which URL names map to which patterns, the
  612. ``reverse()`` function has to import all of your URLconf files and examine
  613. the name of each view. This involves importing each view function. If
  614. there are *any* errors whilst importing any of your view functions, it
  615. will cause ``reverse()`` to raise an error, even if that view function is
  616. not the one you are trying to reverse.
  617. Make sure that any views you reference in your URLconf files exist and can
  618. be imported correctly. Do not include lines that reference views you
  619. haven't written yet, because those views will not be importable.
  620. .. note::
  621. The string returned by :meth:`~django.core.urlresolvers.reverse` is already
  622. :ref:`urlquoted <uri-and-iri-handling>`. For example::
  623. >>> reverse('cities', args=[u'Orléans'])
  624. '.../Orl%C3%A9ans/'
  625. Applying further encoding (such as :meth:`~django.utils.http.urlquote` or
  626. ``urllib.quote``) to the output of :meth:`~django.core.urlresolvers.reverse`
  627. may produce undesirable results.
  628. reverse_lazy()
  629. --------------
  630. .. versionadded:: 1.4
  631. A lazily evaluated version of `reverse()`_.
  632. It is useful for when you need to use a URL reversal before your project's
  633. URLConf is loaded. Some common cases where this function is necessary are:
  634. * providing a reversed URL as the ``url`` attribute of a generic class-based
  635. view.
  636. * providing a reversed URL to a decorator (such as the ``login_url`` argument
  637. for the :func:`django.contrib.auth.decorators.permission_required`
  638. decorator).
  639. * providing a reversed URL as a default value for a parameter in a function's
  640. signature.
  641. resolve()
  642. ---------
  643. The :func:`django.core.urlresolvers.resolve` function can be used for
  644. resolving URL paths to the corresponding view functions. It has the
  645. following signature:
  646. .. function:: resolve(path, urlconf=None)
  647. ``path`` is the URL path you want to resolve. As with
  648. :func:`~django.core.urlresolvers.reverse`, you don't need to
  649. worry about the ``urlconf`` parameter. The function returns a
  650. :class:`ResolverMatch` object that allows you
  651. to access various meta-data about the resolved URL.
  652. If the URL does not resolve, the function raises an
  653. :class:`~django.http.Http404` exception.
  654. .. class:: ResolverMatch
  655. .. attribute:: ResolverMatch.func
  656. The view function that would be used to serve the URL
  657. .. attribute:: ResolverMatch.args
  658. The arguments that would be passed to the view function, as
  659. parsed from the URL.
  660. .. attribute:: ResolverMatch.kwargs
  661. The keyword arguments that would be passed to the view
  662. function, as parsed from the URL.
  663. .. attribute:: ResolverMatch.url_name
  664. The name of the URL pattern that matches the URL.
  665. .. attribute:: ResolverMatch.app_name
  666. The application namespace for the URL pattern that matches the
  667. URL.
  668. .. attribute:: ResolverMatch.namespace
  669. The instance namespace for the URL pattern that matches the
  670. URL.
  671. .. attribute:: ResolverMatch.namespaces
  672. The list of individual namespace components in the full
  673. instance namespace for the URL pattern that matches the URL.
  674. i.e., if the namespace is ``foo:bar``, then namespaces will be
  675. ``['foo', 'bar']``.
  676. A :class:`ResolverMatch` object can then be interrogated to provide
  677. information about the URL pattern that matches a URL::
  678. # Resolve a URL
  679. match = resolve('/some/path/')
  680. # Print the URL pattern that matches the URL
  681. print match.url_name
  682. A :class:`ResolverMatch` object can also be assigned to a triple::
  683. func, args, kwargs = resolve('/some/path/')
  684. .. versionchanged:: 1.3
  685. Triple-assignment exists for backwards-compatibility. Prior to
  686. Django 1.3, :func:`~django.core.urlresolvers.resolve` returned a
  687. triple containing (view function, arguments, keyword arguments);
  688. the :class:`ResolverMatch` object (as well as the namespace and pattern
  689. information it provides) is not available in earlier Django releases.
  690. One possible use of :func:`~django.core.urlresolvers.resolve` would be
  691. to testing if a view would raise a ``Http404`` error before
  692. redirecting to it::
  693. from urlparse import urlparse
  694. from django.core.urlresolvers import resolve
  695. from django.http import HttpResponseRedirect, Http404
  696. def myview(request):
  697. next = request.META.get('HTTP_REFERER', None) or '/'
  698. response = HttpResponseRedirect(next)
  699. # modify the request and response as required, e.g. change locale
  700. # and set corresponding locale cookie
  701. view, args, kwargs = resolve(urlparse(next)[2])
  702. kwargs['request'] = request
  703. try:
  704. view(*args, **kwargs)
  705. except Http404:
  706. return HttpResponseRedirect('/')
  707. return response
  708. permalink()
  709. -----------
  710. The :func:`django.db.models.permalink` decorator is useful for writing short
  711. methods that return a full URL path. For example, a model's
  712. ``get_absolute_url()`` method. See :func:`django.db.models.permalink` for more.
  713. get_script_prefix()
  714. -------------------
  715. .. function:: get_script_prefix()
  716. Normally, you should always use :func:`~django.core.urlresolvers.reverse` or
  717. :func:`~django.db.models.permalink` to define URLs within your application.
  718. However, if your application constructs part of the URL hierarchy itself, you
  719. may occasionally need to generate URLs. In that case, you need to be able to
  720. find the base URL of the Django project within its Web server
  721. (normally, :func:`~django.core.urlresolvers.reverse` takes care of this for
  722. you). In that case, you can call ``get_script_prefix()``, which will return the
  723. script prefix portion of the URL for your Django project. If your Django
  724. project is at the root of its Web server, this is always ``"/"``, but it can be
  725. changed, for instance by using ``django.root`` (see :doc:`How to use
  726. Django with Apache and mod_python </howto/deployment/modpython>`).