PageRenderTime 32ms CodeModel.GetById 18ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/topics/http/urls.txt

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