PageRenderTime 91ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

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