5 .. module:: django.core.urlresolvers
7 A clean, elegant URL scheme is an important detail in a high-quality Web
8 application. Django lets you design URLs however you want, with no framework
11 There's no ``.php`` or ``.cgi`` required, and certainly none of that
12 ``0,2097,1-1-1928,00`` nonsense.
14 See `Cool URIs don't change`_, by World Wide Web creator Tim Berners-Lee, for
15 excellent arguments on why URLs should be clean and usable.
17 .. _Cool URIs don't change: http://www.w3.org/Provider/Style/URI
22 To design URLs for an app, you create a Python module informally called a
23 **URLconf** (URL configuration). This module is pure Python code and
24 is a simple mapping between URL patterns (as simple regular expressions) to
25 Python callback functions (your views).
27 This mapping can be as short or as long as needed. It can reference other
28 mappings. And, because it's pure Python code, it can be constructed
32 Django also allows to translate URLs according to the active language.
33 This process is described in the
34 :ref:`internationalization docs <url-internationalization>`.
36 .. _how-django-processes-a-request:
38 How Django processes a request
39 ==============================
41 When a user requests a page from your Django-powered site, this is the
42 algorithm the system follows to determine which Python code to execute:
44 1. Django determines the root URLconf module to use. Ordinarily,
45 this is the value of the :setting:`ROOT_URLCONF` setting, but if the incoming
46 ``HttpRequest`` object has an attribute called ``urlconf`` (set by
47 middleware :ref:`request processing <request-middleware>`), its value
48 will be used in place of the :setting:`ROOT_URLCONF` setting.
50 2. Django loads that Python module and looks for the variable
51 ``urlpatterns``. This should be a Python list, in the format returned by
52 the function :func:`django.conf.urls.patterns`.
54 3. Django runs through each URL pattern, in order, and stops at the first
55 one that matches the requested URL.
57 4. Once one of the regexes matches, Django imports and calls the given
58 view, which is a simple Python function (or a :doc:`class based view
59 </topics/class-based-views>`). The view gets passed an
60 :class:`~django.http.HttpRequest` as its first argument and any values
61 captured in the regex as remaining arguments.
63 5. If no regex matches, or if an exception is raised during any
64 point in this process, Django invokes an appropriate
65 error-handling view. See `Error handling`_ below.
70 Here's a sample URLconf::
72 from django.conf.urls import patterns, url, include
74 urlpatterns = patterns('',
75 (r'^articles/2003/$', 'news.views.special_case_2003'),
76 (r'^articles/(\d{4})/$', 'news.views.year_archive'),
77 (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
78 (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
83 * To capture a value from the URL, just put parenthesis around it.
85 * There's no need to add a leading slash, because every URL has that. For
86 example, it's ``^articles``, not ``^/articles``.
88 * The ``'r'`` in front of each regular expression string is optional but
89 recommended. It tells Python that a string is "raw" -- that nothing in
90 the string should be escaped. See `Dive Into Python's explanation`_.
94 * A request to ``/articles/2005/03/`` would match the third entry in the
95 list. Django would call the function
96 ``news.views.month_archive(request, '2005', '03')``.
98 * ``/articles/2005/3/`` would not match any URL patterns, because the
99 third entry in the list requires two digits for the month.
101 * ``/articles/2003/`` would match the first pattern in the list, not the
102 second one, because the patterns are tested in order, and the first one
103 is the first test to pass. Feel free to exploit the ordering to insert
104 special cases like this.
106 * ``/articles/2003`` would not match any of these patterns, because each
107 pattern requires that the URL end with a slash.
109 * ``/articles/2003/03/03/`` would match the final pattern. Django would call
110 the function ``news.views.article_detail(request, '2003', '03', '03')``.
112 .. _Dive Into Python's explanation: http://diveintopython.net/regular_expressions/street_addresses.html#re.matching.2.3
117 The above example used simple, *non-named* regular-expression groups (via
118 parenthesis) to capture bits of the URL and pass them as *positional* arguments
119 to a view. In more advanced usage, it's possible to use *named*
120 regular-expression groups to capture URL bits and pass them as *keyword*
123 In Python regular expressions, the syntax for named regular-expression groups
124 is ``(?P<name>pattern)``, where ``name`` is the name of the group and
125 ``pattern`` is some pattern to match.
127 Here's the above example URLconf, rewritten to use named groups::
129 urlpatterns = patterns('',
130 (r'^articles/2003/$', 'news.views.special_case_2003'),
131 (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
132 (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive'),
133 (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$', 'news.views.article_detail'),
136 This accomplishes exactly the same thing as the previous example, with one
137 subtle difference: The captured values are passed to view functions as keyword
138 arguments rather than positional arguments. For example:
140 * A request to ``/articles/2005/03/`` would call the function
141 ``news.views.month_archive(request, year='2005', month='03')``, instead
142 of ``news.views.month_archive(request, '2005', '03')``.
144 * A request to ``/articles/2003/03/03/`` would call the function
145 ``news.views.article_detail(request, year='2003', month='03', day='03')``.
147 In practice, this means your URLconfs are slightly more explicit and less prone
148 to argument-order bugs -- and you can reorder the arguments in your views'
149 function definitions. Of course, these benefits come at the cost of brevity;
150 some developers find the named-group syntax ugly and too verbose.
152 The matching/grouping algorithm
153 -------------------------------
155 Here's the algorithm the URLconf parser follows, with respect to named groups
156 vs. non-named groups in a regular expression:
158 If there are any named arguments, it will use those, ignoring non-named arguments.
159 Otherwise, it will pass all non-named arguments as positional arguments.
161 In both cases, it will pass any extra keyword arguments as keyword arguments.
162 See "Passing extra options to view functions" below.
164 What the URLconf searches against
165 =================================
167 The URLconf searches against the requested URL, as a normal Python string. This
168 does not include GET or POST parameters, or the domain name.
170 For example, in a request to ``http://www.example.com/myapp/``, the URLconf
171 will look for ``myapp/``.
173 In a request to ``http://www.example.com/myapp/?page=3``, the URLconf will look
176 The URLconf doesn't look at the request method. In other words, all request
177 methods -- ``POST``, ``GET``, ``HEAD``, etc. -- will be routed to the same
178 function for the same URL.
180 Syntax of the urlpatterns variable
181 ==================================
183 ``urlpatterns`` should be a Python list, in the format returned by the function
184 :func:`django.conf.urls.patterns`. Always use ``patterns()`` to create
185 the ``urlpatterns`` variable.
187 ``django.conf.urls`` utility functions
188 ======================================
190 .. module:: django.conf.urls
193 Starting with Django 1.4 functions ``patterns``, ``url``, ``include`` plus
194 the ``handler*`` symbols described below live in the ``django.conf.urls``
197 Until Django 1.3 they were located in ``django.conf.urls.defaults``. You
198 still can import them from there but it will be removed in Django 1.6.
203 .. function:: patterns(prefix, pattern_description, ...)
205 A function that takes a prefix, and an arbitrary number of URL patterns, and
206 returns a list of URL patterns in the format Django needs.
208 The first argument to ``patterns()`` is a string ``prefix``. See
209 `The view prefix`_ below.
211 The remaining arguments should be tuples in this format::
213 (regular expression, Python callback function [, optional dictionary [, optional name]])
215 ...where ``optional dictionary`` and ``optional name`` are optional. (See
216 `Passing extra options to view functions`_ below.)
219 Because `patterns()` is a function call, it accepts a maximum of 255
220 arguments (URL patterns, in this case). This is a limit for all Python
221 function calls. This is rarely a problem in practice, because you'll
222 typically structure your URL patterns modularly by using `include()`
223 sections. However, on the off-chance you do hit the 255-argument limit,
224 realize that `patterns()` returns a Python list, so you can split up the
225 construction of the list.
229 urlpatterns = patterns('',
232 urlpatterns += patterns('',
236 Python lists have unlimited size, so there's no limit to how many URL
237 patterns you can construct. The only limit is that you can only create 254
238 at a time (the 255th argument is the initial prefix argument).
243 .. function:: url(regex, view, kwargs=None, name=None, prefix='')
245 You can use the ``url()`` function, instead of a tuple, as an argument to
246 ``patterns()``. This is convenient if you want to specify a name without the
247 optional extra arguments dictionary. For example::
249 urlpatterns = patterns('',
250 url(r'^index/$', index_view, name="main-view"),
254 This function takes five arguments, most of which are optional::
256 url(regex, view, kwargs=None, name=None, prefix='')
258 See `Naming URL patterns`_ for why the ``name`` parameter is useful.
260 The ``prefix`` parameter has the same meaning as the first argument to
261 ``patterns()`` and is only relevant when you're passing a string as the
267 .. function:: include(<module or pattern_list>)
269 A function that takes a full Python import path to another URLconf module that
270 should be "included" in this place.
272 :func:`include` also accepts as an argument an iterable that returns URL
275 See `Including other URLconfs`_ below.
280 When Django can't find a regex matching the requested URL, or when an
281 exception is raised, Django will invoke an error-handling view. The
282 views to use for these cases are specified by three variables which can
283 be set in your root URLconf. Setting these variables in any other
284 URLconf will have no effect.
286 See the documentation on :ref:`customizing error views
287 <customizing-error-views>` for more details.
294 A callable, or a string representing the full Python import path to the view
295 that should be called if the user doesn't have the permissions required to
298 By default, this is ``'django.views.defaults.permission_denied'``. That default
299 value should suffice.
301 See the documentation about :ref:`the 403 (HTTP Forbidden) view
302 <http_forbidden_view>` for more information.
304 .. versionadded:: 1.4
305 ``handler403`` is new in Django 1.4.
312 A callable, or a string representing the full Python import path to the view
313 that should be called if none of the URL patterns match.
315 By default, this is ``'django.views.defaults.page_not_found'``. That default
316 value should suffice.
318 .. versionchanged:: 1.2
319 Previous versions of Django only accepted strings representing import paths.
326 A callable, or a string representing the full Python import path to the view
327 that should be called in case of server errors. Server errors happen when you
328 have runtime errors in view code.
330 By default, this is ``'django.views.defaults.server_error'``. That default
331 value should suffice.
333 .. versionchanged:: 1.2
334 Previous versions of Django only accepted strings representing import paths.
336 Notes on capturing text in URLs
337 ===============================
339 Each captured argument is sent to the view as a plain Python string, regardless
340 of what sort of match the regular expression makes. For example, in this
343 (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
345 ...the ``year`` argument to ``news.views.year_archive()`` will be a string, not
346 an integer, even though the ``\d{4}`` will only match integer strings.
348 A convenient trick is to specify default parameters for your views' arguments.
349 Here's an example URLconf and view::
352 urlpatterns = patterns('',
353 (r'^blog/$', 'blog.views.page'),
354 (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'),
357 # View (in blog/views.py)
358 def page(request, num="1"):
359 # Output the appropriate page of blog entries, according to num.
361 In the above example, both URL patterns point to the same view --
362 ``blog.views.page`` -- but the first pattern doesn't capture anything from the
363 URL. If the first pattern matches, the ``page()`` function will use its
364 default argument for ``num``, ``"1"``. If the second pattern matches,
365 ``page()`` will use whatever ``num`` value was captured by the regex.
370 Each regular expression in a ``urlpatterns`` is compiled the first time it's
371 accessed. This makes the system blazingly fast.
376 You can specify a common prefix in your ``patterns()`` call, to cut down on
379 Here's the example URLconf from the :doc:`Django overview </intro/overview>`::
381 from django.conf.urls import patterns, url, include
383 urlpatterns = patterns('',
384 (r'^articles/(\d{4})/$', 'news.views.year_archive'),
385 (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
386 (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
389 In this example, each view has a common prefix -- ``'news.views'``.
390 Instead of typing that out for each entry in ``urlpatterns``, you can use the
391 first argument to the ``patterns()`` function to specify a prefix to apply to
394 With this in mind, the above example can be written more concisely as::
396 from django.conf.urls import patterns, url, include
398 urlpatterns = patterns('news.views',
399 (r'^articles/(\d{4})/$', 'year_archive'),
400 (r'^articles/(\d{4})/(\d{2})/$', 'month_archive'),
401 (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'article_detail'),
404 Note that you don't put a trailing dot (``"."``) in the prefix. Django puts
405 that in automatically.
407 Multiple view prefixes
408 ----------------------
410 In practice, you'll probably end up mixing and matching views to the point
411 where the views in your ``urlpatterns`` won't have a common prefix. However,
412 you can still take advantage of the view prefix shortcut to remove duplication.
413 Just add multiple ``patterns()`` objects together, like this:
417 from django.conf.urls import patterns, url, include
419 urlpatterns = patterns('',
420 (r'^$', 'django.views.generic.date_based.archive_index'),
421 (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$', 'django.views.generic.date_based.archive_month'),
422 (r'^tag/(?P<tag>\w+)/$', 'weblog.views.tag'),
427 from django.conf.urls import patterns, url, include
429 urlpatterns = patterns('django.views.generic.date_based',
430 (r'^$', 'archive_index'),
431 (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month'),
434 urlpatterns += patterns('weblog.views',
435 (r'^tag/(?P<tag>\w+)/$', 'tag'),
438 Including other URLconfs
439 ========================
441 At any point, your ``urlpatterns`` can "include" other URLconf modules. This
442 essentially "roots" a set of URLs below other ones.
444 For example, here's an excerpt of the URLconf for the `Django Web site`_
445 itself. It includes a number of other URLconfs::
447 from django.conf.urls import patterns, url, include
449 urlpatterns = patterns('',
451 (r'^comments/', include('django.contrib.comments.urls')),
452 (r'^community/', include('django_website.aggregator.urls')),
453 (r'^contact/', include('django_website.contact.urls')),
454 (r'^r/', include('django.conf.urls.shortcut')),
458 Note that the regular expressions in this example don't have a ``$``
459 (end-of-string match character) but do include a trailing slash. Whenever
460 Django encounters ``include()``, it chops off whatever part of the URL matched
461 up to that point and sends the remaining string to the included URLconf for
464 Another possibility is to include additional URL patterns not by specifying the
465 URLconf Python module defining them as the `include`_ argument but by using
466 directly the pattern list as returned by `patterns`_ instead. For example::
468 from django.conf.urls import patterns, url, include
470 extra_patterns = patterns('',
471 url(r'^reports/(?P<id>\d+)/$', 'credit.views.report', name='credit-reports'),
472 url(r'^charge/$', 'credit.views.charge', name='credit-charge'),
475 urlpatterns = patterns('',
476 url(r'^$', 'apps.main.views.homepage', name='site-homepage'),
477 (r'^help/', include('apps.help.urls')),
478 (r'^credit/', include(extra_patterns)),
481 This approach can be seen in use when you deploy an instance of the Django
482 Admin application. The Django Admin is deployed as instances of a
483 :class:`~django.contrib.admin.AdminSite`; each
484 :class:`~django.contrib.admin.AdminSite` instance has an attribute ``urls``
485 that returns the url patterns available to that instance. It is this attribute
486 that you ``include()`` into your projects ``urlpatterns`` when you deploy the
489 .. _`Django Web site`: https://www.djangoproject.com/
494 An included URLconf receives any captured parameters from parent URLconfs, so
495 the following example is valid::
497 # In settings/urls/main.py
498 urlpatterns = patterns('',
499 (r'^(?P<username>\w+)/blog/', include('foo.urls.blog')),
502 # In foo/urls/blog.py
503 urlpatterns = patterns('foo.views',
504 (r'^$', 'blog.index'),
505 (r'^archive/$', 'blog.archive'),
508 In the above example, the captured ``"username"`` variable is passed to the
509 included URLconf, as expected.
511 .. _topics-http-defining-url-namespaces:
513 Defining URL namespaces
514 -----------------------
516 When you need to deploy multiple instances of a single application, it can be
517 helpful to be able to differentiate between instances. This is especially
518 important when using :ref:`named URL patterns <naming-url-patterns>`, since
519 multiple instances of a single application will share named URLs. Namespaces
520 provide a way to tell these named URLs apart.
522 A URL namespace comes in two parts, both of which are strings:
524 * An **application namespace**. This describes the name of the application
525 that is being deployed. Every instance of a single application will have
526 the same application namespace. For example, Django's admin application
527 has the somewhat predictable application namespace of ``admin``.
529 * An **instance namespace**. This identifies a specific instance of an
530 application. Instance namespaces should be unique across your entire
531 project. However, an instance namespace can be the same as the
532 application namespace. This is used to specify a default instance of an
533 application. For example, the default Django Admin instance has an
534 instance namespace of ``admin``.
536 URL Namespaces can be specified in two ways.
538 Firstly, you can provide the application and instance namespace as arguments
539 to ``include()`` when you construct your URL patterns. For example,::
541 (r'^help/', include('apps.help.urls', namespace='foo', app_name='bar')),
543 This will include the URLs defined in ``apps.help.urls`` into the application
544 namespace ``bar``, with the instance namespace ``foo``.
546 Secondly, you can include an object that contains embedded namespace data. If
547 you ``include()`` a ``patterns`` object, that object will be added to the
548 global namespace. However, you can also ``include()`` an object that contains
549 a 3-tuple containing::
551 (<patterns object>, <application namespace>, <instance namespace>)
553 This will include the nominated URL patterns into the given application and
554 instance namespace. For example, the ``urls`` attribute of Django's
555 :class:`~django.contrib.admin.AdminSite` object returns a 3-tuple that contains
556 all the patterns in an admin site, plus the name of the admin instance, and the
557 application namespace ``admin``.
559 Once you have defined namespaced URLs, you can reverse them. For details on
560 reversing namespaced urls, see the documentation on :ref:`reversing namespaced
561 URLs <topics-http-reversing-url-namespaces>`.
563 Passing extra options to view functions
564 =======================================
566 URLconfs have a hook that lets you pass extra arguments to your view functions,
567 as a Python dictionary.
569 Any URLconf tuple can have an optional third element, which should be a
570 dictionary of extra keyword arguments to pass to the view function.
574 urlpatterns = patterns('blog.views',
575 (r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
578 In this example, for a request to ``/blog/2005/``, Django will call the
579 ``blog.views.year_archive()`` view, passing it these keyword arguments::
581 year='2005', foo='bar'
583 This technique is used in :doc:`generic views </ref/generic-views>` and in the
584 :doc:`syndication framework </ref/contrib/syndication>` to pass metadata and
587 .. admonition:: Dealing with conflicts
589 It's possible to have a URL pattern which captures named keyword arguments,
590 and also passes arguments with the same names in its dictionary of extra
591 arguments. When this happens, the arguments in the dictionary will be used
592 instead of the arguments captured in the URL.
594 Passing extra options to ``include()``
595 --------------------------------------
597 Similarly, you can pass extra options to ``include()``. When you pass extra
598 options to ``include()``, *each* line in the included URLconf will be passed
601 For example, these two URLconf sets are functionally identical:
606 urlpatterns = patterns('',
607 (r'^blog/', include('inner'), {'blogid': 3}),
611 urlpatterns = patterns('',
612 (r'^archive/$', 'mysite.views.archive'),
613 (r'^about/$', 'mysite.views.about'),
619 urlpatterns = patterns('',
620 (r'^blog/', include('inner')),
624 urlpatterns = patterns('',
625 (r'^archive/$', 'mysite.views.archive', {'blogid': 3}),
626 (r'^about/$', 'mysite.views.about', {'blogid': 3}),
629 Note that extra options will *always* be passed to *every* line in the included
630 URLconf, regardless of whether the line's view actually accepts those options
631 as valid. For this reason, this technique is only useful if you're certain that
632 every view in the included URLconf accepts the extra options you're passing.
634 Passing callable objects instead of strings
635 ===========================================
637 Some developers find it more natural to pass the actual Python function object
638 rather than a string containing the path to its module. This alternative is
639 supported -- you can pass any callable object as the view.
641 For example, given this URLconf in "string" notation::
643 urlpatterns = patterns('',
644 (r'^archive/$', 'mysite.views.archive'),
645 (r'^about/$', 'mysite.views.about'),
646 (r'^contact/$', 'mysite.views.contact'),
649 You can accomplish the same thing by passing objects rather than strings. Just
650 be sure to import the objects::
652 from mysite.views import archive, about, contact
654 urlpatterns = patterns('',
655 (r'^archive/$', archive),
656 (r'^about/$', about),
657 (r'^contact/$', contact),
660 The following example is functionally identical. It's just a bit more compact
661 because it imports the module that contains the views, rather than importing
662 each view individually::
664 from mysite import views
666 urlpatterns = patterns('',
667 (r'^archive/$', views.archive),
668 (r'^about/$', views.about),
669 (r'^contact/$', views.contact),
672 The style you use is up to you.
674 Note that if you use this technique -- passing objects rather than strings --
675 the view prefix (as explained in "The view prefix" above) will have no effect.
677 Note that :doc:`class based views</topics/class-based-views>` must be
680 from mysite.views import ClassBasedView
682 urlpatterns = patterns('',
683 (r'^myview/$', ClassBasedView.as_view()),
686 .. _naming-url-patterns:
691 It's fairly common to use the same view function in multiple URL patterns in
692 your URLconf. For example, these two URL patterns both point to the ``archive``
695 urlpatterns = patterns('',
696 (r'^archive/(\d{4})/$', archive),
697 (r'^archive-summary/(\d{4})/$', archive, {'summary': True}),
700 This is completely valid, but it leads to problems when you try to do reverse
701 URL matching (through the ``permalink()`` decorator or the :ttag:`url` template
702 tag). Continuing this example, if you wanted to retrieve the URL for the
703 ``archive`` view, Django's reverse URL matcher would get confused, because *two*
704 URL patterns point at that view.
706 To solve this problem, Django supports **named URL patterns**. That is, you can
707 give a name to a URL pattern in order to distinguish it from other patterns
708 using the same view and parameters. Then, you can use this name in reverse URL
711 Here's the above example, rewritten to use named URL patterns::
713 urlpatterns = patterns('',
714 url(r'^archive/(\d{4})/$', archive, name="full-archive"),
715 url(r'^archive-summary/(\d{4})/$', archive, {'summary': True}, "arch-summary"),
718 With these names in place (``full-archive`` and ``arch-summary``), you can
719 target each pattern individually by using its name:
721 .. code-block:: html+django
723 {% url arch-summary 1945 %}
724 {% url full-archive 2007 %}
726 Even though both URL patterns refer to the ``archive`` view here, using the
727 ``name`` parameter to ``url()`` allows you to tell them apart in templates.
729 The string used for the URL name can contain any characters you like. You are
730 not restricted to valid Python names.
734 When you name your URL patterns, make sure you use names that are unlikely
735 to clash with any other application's choice of names. If you call your URL
736 pattern ``comment``, and another application does the same thing, there's
737 no guarantee which URL will be inserted into your template when you use
740 Putting a prefix on your URL names, perhaps derived from the application
741 name, will decrease the chances of collision. We recommend something like
742 ``myapp-comment`` instead of ``comment``.
744 .. _topics-http-reversing-url-namespaces:
749 Namespaced URLs are specified using the ``:`` operator. For example, the main
750 index page of the admin application is referenced using ``admin:index``. This
751 indicates a namespace of ``admin``, and a named URL of ``index``.
753 Namespaces can also be nested. The named URL ``foo:bar:whiz`` would look for
754 a pattern named ``whiz`` in the namespace ``bar`` that is itself defined within
755 the top-level namespace ``foo``.
757 When given a namespaced URL (e.g. ``myapp:index``) to resolve, Django splits
758 the fully qualified name into parts, and then tries the following lookup:
760 1. First, Django looks for a matching application namespace (in this
761 example, ``myapp``). This will yield a list of instances of that
764 2. If there is a *current* application defined, Django finds and returns
765 the URL resolver for that instance. The *current* application can be
766 specified as an attribute on the template context - applications that
767 expect to have multiple deployments should set the ``current_app``
768 attribute on any ``Context`` or ``RequestContext`` that is used to
771 The current application can also be specified manually as an argument
772 to the :func:`reverse()` function.
774 3. If there is no current application. Django looks for a default
775 application instance. The default application instance is the instance
776 that has an instance namespace matching the application namespace (in
777 this example, an instance of the ``myapp`` called ``myapp``).
779 4. If there is no default application instance, Django will pick the last
780 deployed instance of the application, whatever its instance name may be.
782 5. If the provided namespace doesn't match an application namespace in
783 step 1, Django will attempt a direct lookup of the namespace as an
786 If there are nested namespaces, these steps are repeated for each part of the
787 namespace until only the view name is unresolved. The view name will then be
788 resolved into a URL in the namespace that has been found.
790 To show this resolution strategy in action, consider an example of two instances
791 of ``myapp``: one called ``foo``, and one called ``bar``. ``myapp`` has a main
792 index page with a URL named `index`. Using this setup, the following lookups are
795 * If one of the instances is current - say, if we were rendering a utility page
796 in the instance ``bar`` - ``myapp:index`` will resolve to the index page of
797 the instance ``bar``.
799 * If there is no current instance - say, if we were rendering a page
800 somewhere else on the site - ``myapp:index`` will resolve to the last
801 registered instance of ``myapp``. Since there is no default instance,
802 the last instance of ``myapp`` that is registered will be used. This could
803 be ``foo`` or ``bar``, depending on the order they are introduced into the
804 urlpatterns of the project.
806 * ``foo:index`` will always resolve to the index page of the instance ``foo``.
808 If there was also a default instance - i.e., an instance named `myapp` - the
809 following would happen:
811 * If one of the instances is current - say, if we were rendering a utility page
812 in the instance ``bar`` - ``myapp:index`` will resolve to the index page of
813 the instance ``bar``.
815 * If there is no current instance - say, if we were rendering a page somewhere
816 else on the site - ``myapp:index`` will resolve to the index page of the
819 * ``foo:index`` will again resolve to the index page of the instance ``foo``.
822 ``django.core.urlresolvers`` utility functions
823 ==============================================
825 .. currentmodule:: django.core.urlresolvers
830 If you need to use something similar to the :ttag:`url` template tag in
831 your code, Django provides the following function (in the
832 :mod:`django.core.urlresolvers` module):
834 .. function:: reverse(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
836 ``viewname`` is either the function name (either a function reference, or the
837 string version of the name, if you used that form in ``urlpatterns``) or the
838 `URL pattern name`_. Normally, you won't need to worry about the
839 ``urlconf`` parameter and will only pass in the positional and keyword
840 arguments to use in the URL matching. For example::
842 from django.core.urlresolvers import reverse
845 return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
847 .. _URL pattern name: `Naming URL patterns`_
849 The ``reverse()`` function can reverse a large variety of regular expression
850 patterns for URLs, but not every possible one. The main restriction at the
851 moment is that the pattern cannot contain alternative choices using the
852 vertical bar (``"|"``) character. You can quite happily use such patterns for
853 matching against incoming URLs and sending them off to views, but you cannot
854 reverse such patterns.
856 The ``current_app`` argument allows you to provide a hint to the resolver
857 indicating the application to which the currently executing view belongs.
858 This ``current_app`` argument is used as a hint to resolve application
859 namespaces into URLs on specific application instances, according to the
860 :ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
862 You can use ``kwargs`` instead of ``args``. For example::
864 >>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
867 ``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.
869 .. admonition:: Make sure your views are all correct.
871 As part of working out which URL names map to which patterns, the
872 ``reverse()`` function has to import all of your URLconf files and examine
873 the name of each view. This involves importing each view function. If
874 there are *any* errors whilst importing any of your view functions, it
875 will cause ``reverse()`` to raise an error, even if that view function is
876 not the one you are trying to reverse.
878 Make sure that any views you reference in your URLconf files exist and can
879 be imported correctly. Do not include lines that reference views you
880 haven't written yet, because those views will not be importable.
884 The string returned by :meth:`~django.core.urlresolvers.reverse` is already
885 :ref:`urlquoted <uri-and-iri-handling>`. For example::
887 >>> reverse('cities', args=[u'Orléans'])
890 Applying further encoding (such as :meth:`~django.utils.http.urlquote` or
891 ``urllib.quote``) to the output of :meth:`~django.core.urlresolvers.reverse`
892 may produce undesirable results.
897 .. versionadded:: 1.4
899 A lazily evaluated version of `reverse()`_.
901 .. function:: reverse_lazy(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
903 It is useful for when you need to use a URL reversal before your project's
904 URLConf is loaded. Some common cases where this function is necessary are:
906 * providing a reversed URL as the ``url`` attribute of a generic class-based
909 * providing a reversed URL to a decorator (such as the ``login_url`` argument
910 for the :func:`django.contrib.auth.decorators.permission_required`
913 * providing a reversed URL as a default value for a parameter in a function's
919 The :func:`django.core.urlresolvers.resolve` function can be used for
920 resolving URL paths to the corresponding view functions. It has the
923 .. function:: resolve(path, urlconf=None)
925 ``path`` is the URL path you want to resolve. As with
926 :func:`~django.core.urlresolvers.reverse`, you don't need to
927 worry about the ``urlconf`` parameter. The function returns a
928 :class:`ResolverMatch` object that allows you
929 to access various meta-data about the resolved URL.
931 If the URL does not resolve, the function raises an
932 :class:`~django.http.Http404` exception.
934 .. class:: ResolverMatch
936 .. attribute:: ResolverMatch.func
938 The view function that would be used to serve the URL
940 .. attribute:: ResolverMatch.args
942 The arguments that would be passed to the view function, as
945 .. attribute:: ResolverMatch.kwargs
947 The keyword arguments that would be passed to the view
948 function, as parsed from the URL.
950 .. attribute:: ResolverMatch.url_name
952 The name of the URL pattern that matches the URL.
954 .. attribute:: ResolverMatch.app_name
956 The application namespace for the URL pattern that matches the
959 .. attribute:: ResolverMatch.namespace
961 The instance namespace for the URL pattern that matches the
964 .. attribute:: ResolverMatch.namespaces
966 The list of individual namespace components in the full
967 instance namespace for the URL pattern that matches the URL.
968 i.e., if the namespace is ``foo:bar``, then namespaces will be
971 A :class:`ResolverMatch` object can then be interrogated to provide
972 information about the URL pattern that matches a URL::
975 match = resolve('/some/path/')
976 # Print the URL pattern that matches the URL
979 A :class:`ResolverMatch` object can also be assigned to a triple::
981 func, args, kwargs = resolve('/some/path/')
983 .. versionchanged:: 1.3
984 Triple-assignment exists for backwards-compatibility. Prior to
985 Django 1.3, :func:`~django.core.urlresolvers.resolve` returned a
986 triple containing (view function, arguments, keyword arguments);
987 the :class:`ResolverMatch` object (as well as the namespace and pattern
988 information it provides) is not available in earlier Django releases.
990 One possible use of :func:`~django.core.urlresolvers.resolve` would be to test
991 whether a view would raise a ``Http404`` error before redirecting to it::
993 from urlparse import urlparse
994 from django.core.urlresolvers import resolve
995 from django.http import HttpResponseRedirect, Http404
998 next = request.META.get('HTTP_REFERER', None) or '/'
999 response = HttpResponseRedirect(next)
1001 # modify the request and response as required, e.g. change locale
1002 # and set corresponding locale cookie
1004 view, args, kwargs = resolve(urlparse(next)[2])
1005 kwargs['request'] = request
1007 view(*args, **kwargs)
1009 return HttpResponseRedirect('/')
1016 The :func:`django.db.models.permalink` decorator is useful for writing short
1017 methods that return a full URL path. For example, a model's
1018 ``get_absolute_url()`` method. See :func:`django.db.models.permalink` for more.
1023 .. function:: get_script_prefix()
1025 Normally, you should always use :func:`~django.core.urlresolvers.reverse` or
1026 :func:`~django.db.models.permalink` to define URLs within your application.
1027 However, if your application constructs part of the URL hierarchy itself, you
1028 may occasionally need to generate URLs. In that case, you need to be able to
1029 find the base URL of the Django project within its Web server
1030 (normally, :func:`~django.core.urlresolvers.reverse` takes care of this for
1031 you). In that case, you can call ``get_script_prefix()``, which will return the
1032 script prefix portion of the URL for your Django project. If your Django
1033 project is at the root of its Web server, this is always ``"/"``, but it can be
1034 changed, for instance by using ``django.root`` (see :doc:`How to use
1035 Django with Apache and mod_python </howto/deployment/modpython>`).