urls.txt 37 KB

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