<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>URL dispatcher — Django 1.4.21 documentation</title> <link rel="stylesheet" href="../../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../', VERSION: '1.4.21', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <link rel="top" title="Django 1.4.21 documentation" href="../../index.html" /> <link rel="up" title="Handling HTTP requests" href="index.html" /> <link rel="next" title="Writing views" href="views.html" /> <link rel="prev" title="Handling HTTP requests" href="index.html" /> <script type="text/javascript" src="../../templatebuiltins.js"></script> <script type="text/javascript"> (function($) { if (!django_template_builtins) { // templatebuiltins.js missing, do nothing. return; } $(document).ready(function() { // Hyperlink Django template tags and filters var base = "../../ref/templates/builtins.html"; if (base == "#") { // Special case for builtins.html itself base = ""; } // Tags are keywords, class '.k' $("div.highlight\\-html\\+django span.k").each(function(i, elem) { var tagname = $(elem).text(); if ($.inArray(tagname, django_template_builtins.ttags) != -1) { var fragment = tagname.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>"); } }); // Filters are functions, class '.nf' $("div.highlight\\-html\\+django span.nf").each(function(i, elem) { var filtername = $(elem).text(); if ($.inArray(filtername, django_template_builtins.tfilters) != -1) { var fragment = filtername.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>"); } }); }); })(jQuery); </script> </head> <body> <div class="document"> <div id="custom-doc" class="yui-t6"> <div id="hd"> <h1><a href="../../index.html">Django 1.4.21 documentation</a></h1> <div id="global-nav"> <a title="Home page" href="../../index.html">Home</a> | <a title="Table of contents" href="../../contents.html">Table of contents</a> | <a title="Global index" href="../../genindex.html">Index</a> | <a title="Module index" href="../../py-modindex.html">Modules</a> </div> <div class="nav"> « <a href="index.html" title="Handling HTTP requests">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="views.html" title="Writing views">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="topics-http-urls"> <div class="section" id="s-module-django.core.urlresolvers"> <span id="s-url-dispatcher"></span><span id="module-django.core.urlresolvers"></span><span id="url-dispatcher"></span><h1>URL dispatcher<a class="headerlink" href="#module-django.core.urlresolvers" title="Permalink to this headline">¶</a></h1> <p>A clean, elegant URL scheme is an important detail in a high-quality Web application. Django lets you design URLs however you want, with no framework limitations.</p> <p>There’s no <tt class="docutils literal"><span class="pre">.php</span></tt> or <tt class="docutils literal"><span class="pre">.cgi</span></tt> required, and certainly none of that <tt class="docutils literal"><span class="pre">0,2097,1-1-1928,00</span></tt> nonsense.</p> <p>See <a class="reference external" href="http://www.w3.org/Provider/Style/URI">Cool URIs don’t change</a>, by World Wide Web creator Tim Berners-Lee, for excellent arguments on why URLs should be clean and usable.</p> <div class="section" id="s-overview"> <span id="overview"></span><h2>Overview<a class="headerlink" href="#overview" title="Permalink to this headline">¶</a></h2> <p>To design URLs for an app, you create a Python module informally called a <strong>URLconf</strong> (URL configuration). This module is pure Python code and is a simple mapping between URL patterns (as simple regular expressions) to Python callback functions (your views).</p> <p>This mapping can be as short or as long as needed. It can reference other mappings. And, because it’s pure Python code, it can be constructed dynamically.</p> <div class="versionadded"> <span class="title">New in Django 1.4:</span> Django also allows to translate URLs according to the active language. This process is described in the <a class="reference internal" href="../i18n/translation.html#url-internationalization"><em>internationalization docs</em></a>.</div> </div> <div class="section" id="s-how-django-processes-a-request"> <span id="s-id1"></span><span id="how-django-processes-a-request"></span><span id="id1"></span><h2>How Django processes a request<a class="headerlink" href="#how-django-processes-a-request" title="Permalink to this headline">¶</a></h2> <p>When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:</p> <ol class="arabic simple"> <li>Django determines the root URLconf module to use. Ordinarily, this is the value of the <a class="reference internal" href="../../ref/settings.html#std:setting-ROOT_URLCONF"><tt class="xref std std-setting docutils literal"><span class="pre">ROOT_URLCONF</span></tt></a> setting, but if the incoming <tt class="docutils literal"><span class="pre">HttpRequest</span></tt> object has an attribute called <tt class="docutils literal"><span class="pre">urlconf</span></tt> (set by middleware <a class="reference internal" href="middleware.html#request-middleware"><em>request processing</em></a>), its value will be used in place of the <a class="reference internal" href="../../ref/settings.html#std:setting-ROOT_URLCONF"><tt class="xref std std-setting docutils literal"><span class="pre">ROOT_URLCONF</span></tt></a> setting.</li> <li>Django loads that Python module and looks for the variable <tt class="docutils literal"><span class="pre">urlpatterns</span></tt>. This should be a Python list, in the format returned by the function <a class="reference internal" href="#django.conf.urls.patterns" title="django.conf.urls.patterns"><tt class="xref py py-func docutils literal"><span class="pre">django.conf.urls.patterns()</span></tt></a>.</li> <li>Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.</li> <li>Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function (or a <a class="reference internal" href="../class-based-views.html"><em>class based view</em></a>). The view gets passed an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><tt class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></tt></a> as its first argument and any values captured in the regex as remaining arguments.</li> <li>If no regex matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view. See <a class="reference internal" href="#error-handling">Error handling</a> below.</li> </ol> </div> <div class="section" id="s-example"> <span id="example"></span><h2>Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2> <p>Here’s a sample URLconf:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">include</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^articles/2003/$'</span><span class="p">,</span> <span class="s">'news.views.special_case_2003'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^articles/(\d{4})/$'</span><span class="p">,</span> <span class="s">'news.views.year_archive'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^articles/(\d{4})/(\d{2})/$'</span><span class="p">,</span> <span class="s">'news.views.month_archive'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^articles/(\d{4})/(\d{2})/(\d+)/$'</span><span class="p">,</span> <span class="s">'news.views.article_detail'</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>Notes:</p> <ul class="simple"> <li>To capture a value from the URL, just put parenthesis around it.</li> <li>There’s no need to add a leading slash, because every URL has that. For example, it’s <tt class="docutils literal"><span class="pre">^articles</span></tt>, not <tt class="docutils literal"><span class="pre">^/articles</span></tt>.</li> <li>The <tt class="docutils literal"><span class="pre">'r'</span></tt> in front of each regular expression string is optional but recommended. It tells Python that a string is “raw” – that nothing in the string should be escaped. See <a class="reference external" href="http://diveintopython.net/regular_expressions/street_addresses.html#re.matching.2.3">Dive Into Python’s explanation</a>.</li> </ul> <p>Example requests:</p> <ul class="simple"> <li>A request to <tt class="docutils literal"><span class="pre">/articles/2005/03/</span></tt> would match the third entry in the list. Django would call the function <tt class="docutils literal"><span class="pre">news.views.month_archive(request,</span> <span class="pre">'2005',</span> <span class="pre">'03')</span></tt>.</li> <li><tt class="docutils literal"><span class="pre">/articles/2005/3/</span></tt> would not match any URL patterns, because the third entry in the list requires two digits for the month.</li> <li><tt class="docutils literal"><span class="pre">/articles/2003/</span></tt> would match the first pattern in the list, not the second one, because the patterns are tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this.</li> <li><tt class="docutils literal"><span class="pre">/articles/2003</span></tt> would not match any of these patterns, because each pattern requires that the URL end with a slash.</li> <li><tt class="docutils literal"><span class="pre">/articles/2003/03/03/</span></tt> would match the final pattern. Django would call the function <tt class="docutils literal"><span class="pre">news.views.article_detail(request,</span> <span class="pre">'2003',</span> <span class="pre">'03',</span> <span class="pre">'03')</span></tt>.</li> </ul> </div> <div class="section" id="s-named-groups"> <span id="named-groups"></span><h2>Named groups<a class="headerlink" href="#named-groups" title="Permalink to this headline">¶</a></h2> <p>The above example used simple, <em>non-named</em> regular-expression groups (via parenthesis) to capture bits of the URL and pass them as <em>positional</em> arguments to a view. In more advanced usage, it’s possible to use <em>named</em> regular-expression groups to capture URL bits and pass them as <em>keyword</em> arguments to a view.</p> <p>In Python regular expressions, the syntax for named regular-expression groups is <tt class="docutils literal"><span class="pre">(?P<name>pattern)</span></tt>, where <tt class="docutils literal"><span class="pre">name</span></tt> is the name of the group and <tt class="docutils literal"><span class="pre">pattern</span></tt> is some pattern to match.</p> <p>Here’s the above example URLconf, rewritten to use named groups:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^articles/2003/$'</span><span class="p">,</span> <span class="s">'news.views.special_case_2003'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^articles/(?P<year>\d{4})/$'</span><span class="p">,</span> <span class="s">'news.views.year_archive'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$'</span><span class="p">,</span> <span class="s">'news.views.month_archive'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$'</span><span class="p">,</span> <span class="s">'news.views.article_detail'</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>This accomplishes exactly the same thing as the previous example, with one subtle difference: The captured values are passed to view functions as keyword arguments rather than positional arguments. For example:</p> <ul class="simple"> <li>A request to <tt class="docutils literal"><span class="pre">/articles/2005/03/</span></tt> would call the function <tt class="docutils literal"><span class="pre">news.views.month_archive(request,</span> <span class="pre">year='2005',</span> <span class="pre">month='03')</span></tt>, instead of <tt class="docutils literal"><span class="pre">news.views.month_archive(request,</span> <span class="pre">'2005',</span> <span class="pre">'03')</span></tt>.</li> <li>A request to <tt class="docutils literal"><span class="pre">/articles/2003/03/03/</span></tt> would call the function <tt class="docutils literal"><span class="pre">news.views.article_detail(request,</span> <span class="pre">year='2003',</span> <span class="pre">month='03',</span> <span class="pre">day='03')</span></tt>.</li> </ul> <p>In practice, this means your URLconfs are slightly more explicit and less prone to argument-order bugs – and you can reorder the arguments in your views’ function definitions. Of course, these benefits come at the cost of brevity; some developers find the named-group syntax ugly and too verbose.</p> <div class="section" id="s-the-matching-grouping-algorithm"> <span id="the-matching-grouping-algorithm"></span><h3>The matching/grouping algorithm<a class="headerlink" href="#the-matching-grouping-algorithm" title="Permalink to this headline">¶</a></h3> <p>Here’s the algorithm the URLconf parser follows, with respect to named groups vs. non-named groups in a regular expression:</p> <p>If there are any named arguments, it will use those, ignoring non-named arguments. Otherwise, it will pass all non-named arguments as positional arguments.</p> <p>In both cases, it will pass any extra keyword arguments as keyword arguments. See “Passing extra options to view functions” below.</p> </div> </div> <div class="section" id="s-what-the-urlconf-searches-against"> <span id="what-the-urlconf-searches-against"></span><h2>What the URLconf searches against<a class="headerlink" href="#what-the-urlconf-searches-against" title="Permalink to this headline">¶</a></h2> <p>The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.</p> <p>For example, in a request to <tt class="docutils literal"><span class="pre">http://www.example.com/myapp/</span></tt>, the URLconf will look for <tt class="docutils literal"><span class="pre">myapp/</span></tt>.</p> <p>In a request to <tt class="docutils literal"><span class="pre">http://www.example.com/myapp/?page=3</span></tt>, the URLconf will look for <tt class="docutils literal"><span class="pre">myapp/</span></tt>.</p> <p>The URLconf doesn’t look at the request method. In other words, all request methods – <tt class="docutils literal"><span class="pre">POST</span></tt>, <tt class="docutils literal"><span class="pre">GET</span></tt>, <tt class="docutils literal"><span class="pre">HEAD</span></tt>, etc. – will be routed to the same function for the same URL.</p> </div> <div class="section" id="s-syntax-of-the-urlpatterns-variable"> <span id="syntax-of-the-urlpatterns-variable"></span><h2>Syntax of the urlpatterns variable<a class="headerlink" href="#syntax-of-the-urlpatterns-variable" title="Permalink to this headline">¶</a></h2> <p><tt class="docutils literal"><span class="pre">urlpatterns</span></tt> should be a Python list, in the format returned by the function <a class="reference internal" href="#django.conf.urls.patterns" title="django.conf.urls.patterns"><tt class="xref py py-func docutils literal"><span class="pre">django.conf.urls.patterns()</span></tt></a>. Always use <tt class="docutils literal"><span class="pre">patterns()</span></tt> to create the <tt class="docutils literal"><span class="pre">urlpatterns</span></tt> variable.</p> </div> <div class="section" id="s-module-django.conf.urls"> <span id="s-django-conf-urls-utility-functions"></span><span id="module-django.conf.urls"></span><span id="django-conf-urls-utility-functions"></span><h2><tt class="docutils literal"><span class="pre">django.conf.urls</span></tt> utility functions<a class="headerlink" href="#module-django.conf.urls" title="Permalink to this headline">¶</a></h2> <div class="deprecated"> <span class="title">Deprecated in Django 1.4:</span> Starting with Django 1.4 functions <tt class="docutils literal"><span class="pre">patterns</span></tt>, <tt class="docutils literal"><span class="pre">url</span></tt>, <tt class="docutils literal"><span class="pre">include</span></tt> plus the <tt class="docutils literal"><span class="pre">handler*</span></tt> symbols described below live in the <tt class="docutils literal"><span class="pre">django.conf.urls</span></tt> module.<p>Until Django 1.3 they were located in <tt class="docutils literal"><span class="pre">django.conf.urls.defaults</span></tt>. You still can import them from there but it will be removed in Django 1.6.</p> </div> <div class="section" id="s-patterns"> <span id="patterns"></span><h3>patterns<a class="headerlink" href="#patterns" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="django.conf.urls.patterns"> <tt class="descname">patterns</tt>(<em>prefix</em>, <em>pattern_description</em>, <em>...</em>)<a class="headerlink" href="#django.conf.urls.patterns" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>A function that takes a prefix, and an arbitrary number of URL patterns, and returns a list of URL patterns in the format Django needs.</p> <p>The first argument to <tt class="docutils literal"><span class="pre">patterns()</span></tt> is a string <tt class="docutils literal"><span class="pre">prefix</span></tt>. See <a class="reference internal" href="#the-view-prefix">The view prefix</a> below.</p> <p>The remaining arguments should be tuples in this format:</p> <div class="highlight-python"><pre>(regular expression, Python callback function [, optional dictionary [, optional name]])</pre> </div> <p>...where <tt class="docutils literal"><span class="pre">optional</span> <span class="pre">dictionary</span></tt> and <tt class="docutils literal"><span class="pre">optional</span> <span class="pre">name</span></tt> are optional. (See <a class="reference internal" href="#passing-extra-options-to-view-functions">Passing extra options to view functions</a> below.)</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>Because <cite>patterns()</cite> is a function call, it accepts a maximum of 255 arguments (URL patterns, in this case). This is a limit for all Python function calls. This is rarely a problem in practice, because you’ll typically structure your URL patterns modularly by using <cite>include()</cite> sections. However, on the off-chance you do hit the 255-argument limit, realize that <cite>patterns()</cite> returns a Python list, so you can split up the construction of the list.</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="o">...</span> <span class="p">)</span> <span class="n">urlpatterns</span> <span class="o">+=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="o">...</span> <span class="p">)</span> </pre></div> </div> <p class="last">Python lists have unlimited size, so there’s no limit to how many URL patterns you can construct. The only limit is that you can only create 254 at a time (the 255th argument is the initial prefix argument).</p> </div> </div> <div class="section" id="s-url"> <span id="url"></span><h3>url<a class="headerlink" href="#url" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="django.conf.urls.url"> <tt class="descname">url</tt>(<em>regex</em>, <em>view</em>, <em>kwargs=None</em>, <em>name=None</em>, <em>prefix=''</em>)<a class="headerlink" href="#django.conf.urls.url" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>You can use the <tt class="docutils literal"><span class="pre">url()</span></tt> function, instead of a tuple, as an argument to <tt class="docutils literal"><span class="pre">patterns()</span></tt>. This is convenient if you want to specify a name without the optional extra arguments dictionary. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="n">url</span><span class="p">(</span><span class="s">r'^index/$'</span><span class="p">,</span> <span class="n">index_view</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">"main-view"</span><span class="p">),</span> <span class="o">...</span> <span class="p">)</span> </pre></div> </div> <p>This function takes five arguments, most of which are optional:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">url</span><span class="p">(</span><span class="n">regex</span><span class="p">,</span> <span class="n">view</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">prefix</span><span class="o">=</span><span class="s">''</span><span class="p">)</span> </pre></div> </div> <p>See <a class="reference internal" href="#id2">Naming URL patterns</a> for why the <tt class="docutils literal"><span class="pre">name</span></tt> parameter is useful.</p> <p>The <tt class="docutils literal"><span class="pre">prefix</span></tt> parameter has the same meaning as the first argument to <tt class="docutils literal"><span class="pre">patterns()</span></tt> and is only relevant when you’re passing a string as the <tt class="docutils literal"><span class="pre">view</span></tt> parameter.</p> </div> <div class="section" id="s-include"> <span id="include"></span><h3>include<a class="headerlink" href="#include" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="django.conf.urls.include"> <tt class="descname">include</tt>(<em><module or pattern_list></em>)<a class="headerlink" href="#django.conf.urls.include" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>A function that takes a full Python import path to another URLconf module that should be “included” in this place.</p> <p><a class="reference internal" href="#django.conf.urls.include" title="django.conf.urls.include"><tt class="xref py py-func docutils literal"><span class="pre">include()</span></tt></a> also accepts as an argument an iterable that returns URL patterns.</p> <p>See <a class="reference internal" href="#including-other-urlconfs">Including other URLconfs</a> below.</p> </div> </div> <div class="section" id="s-error-handling"> <span id="error-handling"></span><h2>Error handling<a class="headerlink" href="#error-handling" title="Permalink to this headline">¶</a></h2> <p>When Django can’t find a regex matching the requested URL, or when an exception is raised, Django will invoke an error-handling view. The views to use for these cases are specified by three variables which can be set in your root URLconf. Setting these variables in any other URLconf will have no effect.</p> <p>See the documentation on <a class="reference internal" href="views.html#customizing-error-views"><em>customizing error views</em></a> for more details.</p> <div class="section" id="s-handler403"> <span id="handler403"></span><h3>handler403<a class="headerlink" href="#handler403" title="Permalink to this headline">¶</a></h3> <dl class="data"> <dt id="django.conf.urls.handler403"> <tt class="descname">handler403</tt><a class="headerlink" href="#django.conf.urls.handler403" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>A callable, or a string representing the full Python import path to the view that should be called if the user doesn’t have the permissions required to access a resource.</p> <p>By default, this is <tt class="docutils literal"><span class="pre">'django.views.defaults.permission_denied'</span></tt>. That default value should suffice.</p> <p>See the documentation about <a class="reference internal" href="views.html#http-forbidden-view"><em>the 403 (HTTP Forbidden) view</em></a> for more information.</p> <div class="versionadded"> <span class="title">New in Django 1.4:</span> <tt class="docutils literal"><span class="pre">handler403</span></tt> is new in Django 1.4.</div> </div> <div class="section" id="s-handler404"> <span id="handler404"></span><h3>handler404<a class="headerlink" href="#handler404" title="Permalink to this headline">¶</a></h3> <dl class="data"> <dt id="django.conf.urls.handler404"> <tt class="descname">handler404</tt><a class="headerlink" href="#django.conf.urls.handler404" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>A callable, or a string representing the full Python import path to the view that should be called if none of the URL patterns match.</p> <p>By default, this is <tt class="docutils literal"><span class="pre">'django.views.defaults.page_not_found'</span></tt>. That default value should suffice.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.2:</span> Previous versions of Django only accepted strings representing import paths.</div> </div> <div class="section" id="s-handler500"> <span id="handler500"></span><h3>handler500<a class="headerlink" href="#handler500" title="Permalink to this headline">¶</a></h3> <dl class="data"> <dt id="django.conf.urls.handler500"> <tt class="descname">handler500</tt><a class="headerlink" href="#django.conf.urls.handler500" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>A callable, or a string representing the full Python import path to the view that should be called in case of server errors. Server errors happen when you have runtime errors in view code.</p> <p>By default, this is <tt class="docutils literal"><span class="pre">'django.views.defaults.server_error'</span></tt>. That default value should suffice.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.2:</span> Previous versions of Django only accepted strings representing import paths.</div> </div> </div> <div class="section" id="s-notes-on-capturing-text-in-urls"> <span id="notes-on-capturing-text-in-urls"></span><h2>Notes on capturing text in URLs<a class="headerlink" href="#notes-on-capturing-text-in-urls" title="Permalink to this headline">¶</a></h2> <p>Each captured argument is sent to the view as a plain Python string, regardless of what sort of match the regular expression makes. For example, in this URLconf line:</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">(</span><span class="s">r'^articles/(?P<year>\d{4})/$'</span><span class="p">,</span> <span class="s">'news.views.year_archive'</span><span class="p">),</span> </pre></div> </div> <p>...the <tt class="docutils literal"><span class="pre">year</span></tt> argument to <tt class="docutils literal"><span class="pre">news.views.year_archive()</span></tt> will be a string, not an integer, even though the <tt class="docutils literal"><span class="pre">\d{4}</span></tt> will only match integer strings.</p> <p>A convenient trick is to specify default parameters for your views’ arguments. Here’s an example URLconf and view:</p> <div class="highlight-python"><pre># URLconf urlpatterns = patterns('', (r'^blog/$', 'blog.views.page'), (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'), ) # View (in blog/views.py) def page(request, num="1"): # Output the appropriate page of blog entries, according to num.</pre> </div> <p>In the above example, both URL patterns point to the same view – <tt class="docutils literal"><span class="pre">blog.views.page</span></tt> – but the first pattern doesn’t capture anything from the URL. If the first pattern matches, the <tt class="docutils literal"><span class="pre">page()</span></tt> function will use its default argument for <tt class="docutils literal"><span class="pre">num</span></tt>, <tt class="docutils literal"><span class="pre">"1"</span></tt>. If the second pattern matches, <tt class="docutils literal"><span class="pre">page()</span></tt> will use whatever <tt class="docutils literal"><span class="pre">num</span></tt> value was captured by the regex.</p> </div> <div class="section" id="s-performance"> <span id="performance"></span><h2>Performance<a class="headerlink" href="#performance" title="Permalink to this headline">¶</a></h2> <p>Each regular expression in a <tt class="docutils literal"><span class="pre">urlpatterns</span></tt> is compiled the first time it’s accessed. This makes the system blazingly fast.</p> </div> <div class="section" id="s-the-view-prefix"> <span id="the-view-prefix"></span><h2>The view prefix<a class="headerlink" href="#the-view-prefix" title="Permalink to this headline">¶</a></h2> <p>You can specify a common prefix in your <tt class="docutils literal"><span class="pre">patterns()</span></tt> call, to cut down on code duplication.</p> <p>Here’s the example URLconf from the <a class="reference internal" href="../../intro/overview.html"><em>Django overview</em></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">include</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^articles/(\d{4})/$'</span><span class="p">,</span> <span class="s">'news.views.year_archive'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^articles/(\d{4})/(\d{2})/$'</span><span class="p">,</span> <span class="s">'news.views.month_archive'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^articles/(\d{4})/(\d{2})/(\d+)/$'</span><span class="p">,</span> <span class="s">'news.views.article_detail'</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>In this example, each view has a common prefix – <tt class="docutils literal"><span class="pre">'news.views'</span></tt>. Instead of typing that out for each entry in <tt class="docutils literal"><span class="pre">urlpatterns</span></tt>, you can use the first argument to the <tt class="docutils literal"><span class="pre">patterns()</span></tt> function to specify a prefix to apply to each view function.</p> <p>With this in mind, the above example can be written more concisely as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">include</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">'news.views'</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^articles/(\d{4})/$'</span><span class="p">,</span> <span class="s">'year_archive'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^articles/(\d{4})/(\d{2})/$'</span><span class="p">,</span> <span class="s">'month_archive'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^articles/(\d{4})/(\d{2})/(\d+)/$'</span><span class="p">,</span> <span class="s">'article_detail'</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>Note that you don’t put a trailing dot (<tt class="docutils literal"><span class="pre">"."</span></tt>) in the prefix. Django puts that in automatically.</p> <div class="section" id="s-multiple-view-prefixes"> <span id="multiple-view-prefixes"></span><h3>Multiple view prefixes<a class="headerlink" href="#multiple-view-prefixes" title="Permalink to this headline">¶</a></h3> <p>In practice, you’ll probably end up mixing and matching views to the point where the views in your <tt class="docutils literal"><span class="pre">urlpatterns</span></tt> won’t have a common prefix. However, you can still take advantage of the view prefix shortcut to remove duplication. Just add multiple <tt class="docutils literal"><span class="pre">patterns()</span></tt> objects together, like this:</p> <p>Old:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">include</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="s">'django.views.generic.date_based.archive_index'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$'</span><span class="p">,</span> <span class="s">'django.views.generic.date_based.archive_month'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^tag/(?P<tag>\w+)/$'</span><span class="p">,</span> <span class="s">'weblog.views.tag'</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>New:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">include</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">'django.views.generic.date_based'</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="s">'archive_index'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$'</span><span class="p">,</span><span class="s">'archive_month'</span><span class="p">),</span> <span class="p">)</span> <span class="n">urlpatterns</span> <span class="o">+=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">'weblog.views'</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^tag/(?P<tag>\w+)/$'</span><span class="p">,</span> <span class="s">'tag'</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> </div> </div> <div class="section" id="s-including-other-urlconfs"> <span id="including-other-urlconfs"></span><h2>Including other URLconfs<a class="headerlink" href="#including-other-urlconfs" title="Permalink to this headline">¶</a></h2> <p>At any point, your <tt class="docutils literal"><span class="pre">urlpatterns</span></tt> can “include” other URLconf modules. This essentially “roots” a set of URLs below other ones.</p> <p>For example, here’s an excerpt of the URLconf for the <a class="reference external" href="https://www.djangoproject.com/">Django Web site</a> itself. It includes a number of other URLconfs:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">include</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="c"># ... snip ...</span> <span class="p">(</span><span class="s">r'^comments/'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s">'django.contrib.comments.urls'</span><span class="p">)),</span> <span class="p">(</span><span class="s">r'^community/'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s">'django_website.aggregator.urls'</span><span class="p">)),</span> <span class="p">(</span><span class="s">r'^contact/'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s">'django_website.contact.urls'</span><span class="p">)),</span> <span class="p">(</span><span class="s">r'^r/'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s">'django.conf.urls.shortcut'</span><span class="p">)),</span> <span class="c"># ... snip ...</span> <span class="p">)</span> </pre></div> </div> <p>Note that the regular expressions in this example don’t have a <tt class="docutils literal"><span class="pre">$</span></tt> (end-of-string match character) but do include a trailing slash. Whenever Django encounters <tt class="docutils literal"><span class="pre">include()</span></tt>, it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.</p> <p>Another possibility is to include additional URL patterns not by specifying the URLconf Python module defining them as the <a class="reference internal" href="#include">include</a> argument but by using directly the pattern list as returned by <a class="reference internal" href="#patterns">patterns</a> instead. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span><span class="p">,</span> <span class="n">url</span><span class="p">,</span> <span class="n">include</span> <span class="n">extra_patterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="n">url</span><span class="p">(</span><span class="s">r'^reports/(?P<id>\d+)/$'</span><span class="p">,</span> <span class="s">'credit.views.report'</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'credit-reports'</span><span class="p">),</span> <span class="n">url</span><span class="p">(</span><span class="s">r'^charge/$'</span><span class="p">,</span> <span class="s">'credit.views.charge'</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'credit-charge'</span><span class="p">),</span> <span class="p">)</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="n">url</span><span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="s">'apps.main.views.homepage'</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">'site-homepage'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^help/'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s">'apps.help.urls'</span><span class="p">)),</span> <span class="p">(</span><span class="s">r'^credit/'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="n">extra_patterns</span><span class="p">)),</span> <span class="p">)</span> </pre></div> </div> <p>This approach can be seen in use when you deploy an instance of the Django Admin application. The Django Admin is deployed as instances of a <a class="reference internal" href="../../ref/contrib/admin/index.html#django.contrib.admin.AdminSite" title="django.contrib.admin.AdminSite"><tt class="xref py py-class docutils literal"><span class="pre">AdminSite</span></tt></a>; each <a class="reference internal" href="../../ref/contrib/admin/index.html#django.contrib.admin.AdminSite" title="django.contrib.admin.AdminSite"><tt class="xref py py-class docutils literal"><span class="pre">AdminSite</span></tt></a> instance has an attribute <tt class="docutils literal"><span class="pre">urls</span></tt> that returns the url patterns available to that instance. It is this attribute that you <tt class="docutils literal"><span class="pre">include()</span></tt> into your projects <tt class="docutils literal"><span class="pre">urlpatterns</span></tt> when you deploy the admin instance.</p> <div class="section" id="s-captured-parameters"> <span id="captured-parameters"></span><h3>Captured parameters<a class="headerlink" href="#captured-parameters" title="Permalink to this headline">¶</a></h3> <p>An included URLconf receives any captured parameters from parent URLconfs, so the following example is valid:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># In settings/urls/main.py</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^(?P<username>\w+)/blog/'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s">'foo.urls.blog'</span><span class="p">)),</span> <span class="p">)</span> <span class="c"># In foo/urls/blog.py</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">'foo.views'</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="s">'blog.index'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^archive/$'</span><span class="p">,</span> <span class="s">'blog.archive'</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>In the above example, the captured <tt class="docutils literal"><span class="pre">"username"</span></tt> variable is passed to the included URLconf, as expected.</p> </div> <div class="section" id="s-defining-url-namespaces"> <span id="s-topics-http-defining-url-namespaces"></span><span id="defining-url-namespaces"></span><span id="topics-http-defining-url-namespaces"></span><h3>Defining URL namespaces<a class="headerlink" href="#defining-url-namespaces" title="Permalink to this headline">¶</a></h3> <p>When you need to deploy multiple instances of a single application, it can be helpful to be able to differentiate between instances. This is especially important when using <a class="reference internal" href="#naming-url-patterns"><em>named URL patterns</em></a>, since multiple instances of a single application will share named URLs. Namespaces provide a way to tell these named URLs apart.</p> <p>A URL namespace comes in two parts, both of which are strings:</p> <ul class="simple"> <li>An <strong>application namespace</strong>. This describes the name of the application that is being deployed. Every instance of a single application will have the same application namespace. For example, Django’s admin application has the somewhat predictable application namespace of <tt class="docutils literal"><span class="pre">admin</span></tt>.</li> <li>An <strong>instance namespace</strong>. This identifies a specific instance of an application. Instance namespaces should be unique across your entire project. However, an instance namespace can be the same as the application namespace. This is used to specify a default instance of an application. For example, the default Django Admin instance has an instance namespace of <tt class="docutils literal"><span class="pre">admin</span></tt>.</li> </ul> <p>URL Namespaces can be specified in two ways.</p> <p>Firstly, you can provide the application and instance namespace as arguments to <tt class="docutils literal"><span class="pre">include()</span></tt> when you construct your URL patterns. For example,:</p> <div class="highlight-python"><div class="highlight"><pre><span class="p">(</span><span class="s">r'^help/'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s">'apps.help.urls'</span><span class="p">,</span> <span class="n">namespace</span><span class="o">=</span><span class="s">'foo'</span><span class="p">,</span> <span class="n">app_name</span><span class="o">=</span><span class="s">'bar'</span><span class="p">)),</span> </pre></div> </div> <p>This will include the URLs defined in <tt class="docutils literal"><span class="pre">apps.help.urls</span></tt> into the application namespace <tt class="docutils literal"><span class="pre">bar</span></tt>, with the instance namespace <tt class="docutils literal"><span class="pre">foo</span></tt>.</p> <p>Secondly, you can include an object that contains embedded namespace data. If you <tt class="docutils literal"><span class="pre">include()</span></tt> a <tt class="docutils literal"><span class="pre">patterns</span></tt> object, that object will be added to the global namespace. However, you can also <tt class="docutils literal"><span class="pre">include()</span></tt> an object that contains a 3-tuple containing:</p> <div class="highlight-python"><pre>(<patterns object>, <application namespace>, <instance namespace>)</pre> </div> <p>This will include the nominated URL patterns into the given application and instance namespace. For example, the <tt class="docutils literal"><span class="pre">urls</span></tt> attribute of Django’s <a class="reference internal" href="../../ref/contrib/admin/index.html#django.contrib.admin.AdminSite" title="django.contrib.admin.AdminSite"><tt class="xref py py-class docutils literal"><span class="pre">AdminSite</span></tt></a> object returns a 3-tuple that contains all the patterns in an admin site, plus the name of the admin instance, and the application namespace <tt class="docutils literal"><span class="pre">admin</span></tt>.</p> <p>Once you have defined namespaced URLs, you can reverse them. For details on reversing namespaced urls, see the documentation on <a class="reference internal" href="#topics-http-reversing-url-namespaces"><em>reversing namespaced URLs</em></a>.</p> </div> </div> <div class="section" id="s-passing-extra-options-to-view-functions"> <span id="passing-extra-options-to-view-functions"></span><h2>Passing extra options to view functions<a class="headerlink" href="#passing-extra-options-to-view-functions" title="Permalink to this headline">¶</a></h2> <p>URLconfs have a hook that lets you pass extra arguments to your view functions, as a Python dictionary.</p> <p>Any URLconf tuple can have an optional third element, which should be a dictionary of extra keyword arguments to pass to the view function.</p> <p>For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">'blog.views'</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^blog/(?P<year>\d{4})/$'</span><span class="p">,</span> <span class="s">'year_archive'</span><span class="p">,</span> <span class="p">{</span><span class="s">'foo'</span><span class="p">:</span> <span class="s">'bar'</span><span class="p">}),</span> <span class="p">)</span> </pre></div> </div> <p>In this example, for a request to <tt class="docutils literal"><span class="pre">/blog/2005/</span></tt>, Django will call the <tt class="docutils literal"><span class="pre">blog.views.year_archive()</span></tt> view, passing it these keyword arguments:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">year</span><span class="o">=</span><span class="s">'2005'</span><span class="p">,</span> <span class="n">foo</span><span class="o">=</span><span class="s">'bar'</span> </pre></div> </div> <p>This technique is used in <a class="reference internal" href="../../ref/generic-views.html"><em>generic views</em></a> and in the <a class="reference internal" href="../../ref/contrib/syndication.html"><em>syndication framework</em></a> to pass metadata and options to views.</p> <div class="admonition-dealing-with-conflicts admonition"> <p class="first admonition-title">Dealing with conflicts</p> <p class="last">It’s possible to have a URL pattern which captures named keyword arguments, and also passes arguments with the same names in its dictionary of extra arguments. When this happens, the arguments in the dictionary will be used instead of the arguments captured in the URL.</p> </div> <div class="section" id="s-passing-extra-options-to-include"> <span id="passing-extra-options-to-include"></span><h3>Passing extra options to <tt class="docutils literal"><span class="pre">include()</span></tt><a class="headerlink" href="#passing-extra-options-to-include" title="Permalink to this headline">¶</a></h3> <p>Similarly, you can pass extra options to <tt class="docutils literal"><span class="pre">include()</span></tt>. When you pass extra options to <tt class="docutils literal"><span class="pre">include()</span></tt>, <em>each</em> line in the included URLconf will be passed the extra options.</p> <p>For example, these two URLconf sets are functionally identical:</p> <p>Set one:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># main.py</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^blog/'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s">'inner'</span><span class="p">),</span> <span class="p">{</span><span class="s">'blogid'</span><span class="p">:</span> <span class="mi">3</span><span class="p">}),</span> <span class="p">)</span> <span class="c"># inner.py</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^archive/$'</span><span class="p">,</span> <span class="s">'mysite.views.archive'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^about/$'</span><span class="p">,</span> <span class="s">'mysite.views.about'</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>Set two:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># main.py</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^blog/'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s">'inner'</span><span class="p">)),</span> <span class="p">)</span> <span class="c"># inner.py</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^archive/$'</span><span class="p">,</span> <span class="s">'mysite.views.archive'</span><span class="p">,</span> <span class="p">{</span><span class="s">'blogid'</span><span class="p">:</span> <span class="mi">3</span><span class="p">}),</span> <span class="p">(</span><span class="s">r'^about/$'</span><span class="p">,</span> <span class="s">'mysite.views.about'</span><span class="p">,</span> <span class="p">{</span><span class="s">'blogid'</span><span class="p">:</span> <span class="mi">3</span><span class="p">}),</span> <span class="p">)</span> </pre></div> </div> <p>Note that extra options will <em>always</em> be passed to <em>every</em> line in the included URLconf, regardless of whether the line’s view actually accepts those options as valid. For this reason, this technique is only useful if you’re certain that every view in the included URLconf accepts the extra options you’re passing.</p> </div> </div> <div class="section" id="s-passing-callable-objects-instead-of-strings"> <span id="passing-callable-objects-instead-of-strings"></span><h2>Passing callable objects instead of strings<a class="headerlink" href="#passing-callable-objects-instead-of-strings" title="Permalink to this headline">¶</a></h2> <p>Some developers find it more natural to pass the actual Python function object rather than a string containing the path to its module. This alternative is supported – you can pass any callable object as the view.</p> <p>For example, given this URLconf in “string” notation:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^archive/$'</span><span class="p">,</span> <span class="s">'mysite.views.archive'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^about/$'</span><span class="p">,</span> <span class="s">'mysite.views.about'</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^contact/$'</span><span class="p">,</span> <span class="s">'mysite.views.contact'</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>You can accomplish the same thing by passing objects rather than strings. Just be sure to import the objects:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">mysite.views</span> <span class="kn">import</span> <span class="n">archive</span><span class="p">,</span> <span class="n">about</span><span class="p">,</span> <span class="n">contact</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^archive/$'</span><span class="p">,</span> <span class="n">archive</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^about/$'</span><span class="p">,</span> <span class="n">about</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^contact/$'</span><span class="p">,</span> <span class="n">contact</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>The following example is functionally identical. It’s just a bit more compact because it imports the module that contains the views, rather than importing each view individually:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">mysite</span> <span class="kn">import</span> <span class="n">views</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^archive/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">archive</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^about/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">about</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^contact/$'</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">contact</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>The style you use is up to you.</p> <p>Note that if you use this technique – passing objects rather than strings – the view prefix (as explained in “The view prefix” above) will have no effect.</p> <p>Note that <a class="reference internal" href="../class-based-views.html"><em>class based views</em></a> must be imported:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">mysite.views</span> <span class="kn">import</span> <span class="n">ClassBasedView</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^myview/$'</span><span class="p">,</span> <span class="n">ClassBasedView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()),</span> <span class="p">)</span> </pre></div> </div> </div> <div class="section" id="s-naming-url-patterns"> <span id="s-id2"></span><span id="naming-url-patterns"></span><span id="id2"></span><h2>Naming URL patterns<a class="headerlink" href="#naming-url-patterns" title="Permalink to this headline">¶</a></h2> <p>It’s fairly common to use the same view function in multiple URL patterns in your URLconf. For example, these two URL patterns both point to the <tt class="docutils literal"><span class="pre">archive</span></tt> view:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="p">(</span><span class="s">r'^archive/(\d{4})/$'</span><span class="p">,</span> <span class="n">archive</span><span class="p">),</span> <span class="p">(</span><span class="s">r'^archive-summary/(\d{4})/$'</span><span class="p">,</span> <span class="n">archive</span><span class="p">,</span> <span class="p">{</span><span class="s">'summary'</span><span class="p">:</span> <span class="bp">True</span><span class="p">}),</span> <span class="p">)</span> </pre></div> </div> <p>This is completely valid, but it leads to problems when you try to do reverse URL matching (through the <tt class="docutils literal"><span class="pre">permalink()</span></tt> decorator or the <a class="reference internal" href="../../ref/templates/builtins.html#std:templatetag-url"><tt class="xref std std-ttag docutils literal"><span class="pre">url</span></tt></a> template tag). Continuing this example, if you wanted to retrieve the URL for the <tt class="docutils literal"><span class="pre">archive</span></tt> view, Django’s reverse URL matcher would get confused, because <em>two</em> URL patterns point at that view.</p> <p>To solve this problem, Django supports <strong>named URL patterns</strong>. That is, you can give a name to a URL pattern in order to distinguish it from other patterns using the same view and parameters. Then, you can use this name in reverse URL matching.</p> <p>Here’s the above example, rewritten to use named URL patterns:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span> <span class="n">url</span><span class="p">(</span><span class="s">r'^archive/(\d{4})/$'</span><span class="p">,</span> <span class="n">archive</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">"full-archive"</span><span class="p">),</span> <span class="n">url</span><span class="p">(</span><span class="s">r'^archive-summary/(\d{4})/$'</span><span class="p">,</span> <span class="n">archive</span><span class="p">,</span> <span class="p">{</span><span class="s">'summary'</span><span class="p">:</span> <span class="bp">True</span><span class="p">},</span> <span class="s">"arch-summary"</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>With these names in place (<tt class="docutils literal"><span class="pre">full-archive</span></tt> and <tt class="docutils literal"><span class="pre">arch-summary</span></tt>), you can target each pattern individually by using its name:</p> <div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">url</span> <span class="nv">arch-summary</span> <span class="m">1945</span> <span class="cp">%}</span> <span class="cp">{%</span> <span class="k">url</span> <span class="nv">full-archive</span> <span class="m">2007</span> <span class="cp">%}</span> </pre></div> </div> <p>Even though both URL patterns refer to the <tt class="docutils literal"><span class="pre">archive</span></tt> view here, using the <tt class="docutils literal"><span class="pre">name</span></tt> parameter to <tt class="docutils literal"><span class="pre">url()</span></tt> allows you to tell them apart in templates.</p> <p>The string used for the URL name can contain any characters you like. You are not restricted to valid Python names.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>When you name your URL patterns, make sure you use names that are unlikely to clash with any other application’s choice of names. If you call your URL pattern <tt class="docutils literal"><span class="pre">comment</span></tt>, and another application does the same thing, there’s no guarantee which URL will be inserted into your template when you use this name.</p> <p class="last">Putting a prefix on your URL names, perhaps derived from the application name, will decrease the chances of collision. We recommend something like <tt class="docutils literal"><span class="pre">myapp-comment</span></tt> instead of <tt class="docutils literal"><span class="pre">comment</span></tt>.</p> </div> <div class="section" id="s-url-namespaces"> <span id="s-topics-http-reversing-url-namespaces"></span><span id="url-namespaces"></span><span id="topics-http-reversing-url-namespaces"></span><h3>URL namespaces<a class="headerlink" href="#url-namespaces" title="Permalink to this headline">¶</a></h3> <p>Namespaced URLs are specified using the <tt class="docutils literal"><span class="pre">:</span></tt> operator. For example, the main index page of the admin application is referenced using <tt class="docutils literal"><span class="pre">admin:index</span></tt>. This indicates a namespace of <tt class="docutils literal"><span class="pre">admin</span></tt>, and a named URL of <tt class="docutils literal"><span class="pre">index</span></tt>.</p> <p>Namespaces can also be nested. The named URL <tt class="docutils literal"><span class="pre">foo:bar:whiz</span></tt> would look for a pattern named <tt class="docutils literal"><span class="pre">whiz</span></tt> in the namespace <tt class="docutils literal"><span class="pre">bar</span></tt> that is itself defined within the top-level namespace <tt class="docutils literal"><span class="pre">foo</span></tt>.</p> <p>When given a namespaced URL (e.g. <tt class="docutils literal"><span class="pre">myapp:index</span></tt>) to resolve, Django splits the fully qualified name into parts, and then tries the following lookup:</p> <ol class="arabic"> <li><p class="first">First, Django looks for a matching application namespace (in this example, <tt class="docutils literal"><span class="pre">myapp</span></tt>). This will yield a list of instances of that application.</p> </li> <li><p class="first">If there is a <em>current</em> application defined, Django finds and returns the URL resolver for that instance. The <em>current</em> application can be specified as an attribute on the template context - applications that expect to have multiple deployments should set the <tt class="docutils literal"><span class="pre">current_app</span></tt> attribute on any <tt class="docutils literal"><span class="pre">Context</span></tt> or <tt class="docutils literal"><span class="pre">RequestContext</span></tt> that is used to render a template.</p> <p>The current application can also be specified manually as an argument to the <tt class="xref py py-func docutils literal"><span class="pre">reverse()</span></tt> function.</p> </li> <li><p class="first">If there is no current application. Django looks for a default application instance. The default application instance is the instance that has an instance namespace matching the application namespace (in this example, an instance of the <tt class="docutils literal"><span class="pre">myapp</span></tt> called <tt class="docutils literal"><span class="pre">myapp</span></tt>).</p> </li> <li><p class="first">If there is no default application instance, Django will pick the last deployed instance of the application, whatever its instance name may be.</p> </li> <li><p class="first">If the provided namespace doesn’t match an application namespace in step 1, Django will attempt a direct lookup of the namespace as an instance namespace.</p> </li> </ol> <p>If there are nested namespaces, these steps are repeated for each part of the namespace until only the view name is unresolved. The view name will then be resolved into a URL in the namespace that has been found.</p> <p>To show this resolution strategy in action, consider an example of two instances of <tt class="docutils literal"><span class="pre">myapp</span></tt>: one called <tt class="docutils literal"><span class="pre">foo</span></tt>, and one called <tt class="docutils literal"><span class="pre">bar</span></tt>. <tt class="docutils literal"><span class="pre">myapp</span></tt> has a main index page with a URL named <cite>index</cite>. Using this setup, the following lookups are possible:</p> <ul class="simple"> <li>If one of the instances is current - say, if we were rendering a utility page in the instance <tt class="docutils literal"><span class="pre">bar</span></tt> - <tt class="docutils literal"><span class="pre">myapp:index</span></tt> will resolve to the index page of the instance <tt class="docutils literal"><span class="pre">bar</span></tt>.</li> <li>If there is no current instance - say, if we were rendering a page somewhere else on the site - <tt class="docutils literal"><span class="pre">myapp:index</span></tt> will resolve to the last registered instance of <tt class="docutils literal"><span class="pre">myapp</span></tt>. Since there is no default instance, the last instance of <tt class="docutils literal"><span class="pre">myapp</span></tt> that is registered will be used. This could be <tt class="docutils literal"><span class="pre">foo</span></tt> or <tt class="docutils literal"><span class="pre">bar</span></tt>, depending on the order they are introduced into the urlpatterns of the project.</li> <li><tt class="docutils literal"><span class="pre">foo:index</span></tt> will always resolve to the index page of the instance <tt class="docutils literal"><span class="pre">foo</span></tt>.</li> </ul> <p>If there was also a default instance - i.e., an instance named <cite>myapp</cite> - the following would happen:</p> <ul class="simple"> <li>If one of the instances is current - say, if we were rendering a utility page in the instance <tt class="docutils literal"><span class="pre">bar</span></tt> - <tt class="docutils literal"><span class="pre">myapp:index</span></tt> will resolve to the index page of the instance <tt class="docutils literal"><span class="pre">bar</span></tt>.</li> <li>If there is no current instance - say, if we were rendering a page somewhere else on the site - <tt class="docutils literal"><span class="pre">myapp:index</span></tt> will resolve to the index page of the default instance.</li> <li><tt class="docutils literal"><span class="pre">foo:index</span></tt> will again resolve to the index page of the instance <tt class="docutils literal"><span class="pre">foo</span></tt>.</li> </ul> </div> </div> <div class="section" id="s-django-core-urlresolvers-utility-functions"> <span id="django-core-urlresolvers-utility-functions"></span><h2><tt class="docutils literal"><span class="pre">django.core.urlresolvers</span></tt> utility functions<a class="headerlink" href="#django-core-urlresolvers-utility-functions" title="Permalink to this headline">¶</a></h2> <div class="section" id="s-reverse"> <span id="reverse"></span><h3>reverse()<a class="headerlink" href="#reverse" title="Permalink to this headline">¶</a></h3> <p>If you need to use something similar to the <a class="reference internal" href="../../ref/templates/builtins.html#std:templatetag-url"><tt class="xref std std-ttag docutils literal"><span class="pre">url</span></tt></a> template tag in your code, Django provides the following function (in the <a class="reference internal" href="#module-django.core.urlresolvers" title="django.core.urlresolvers"><tt class="xref py py-mod docutils literal"><span class="pre">django.core.urlresolvers</span></tt></a> module):</p> <dl class="function"> <dt id="django.core.urlresolvers.reverse"> <tt class="descname">reverse</tt>(<em>viewname</em><span class="optional">[</span>, <em>urlconf=None</em>, <em>args=None</em>, <em>kwargs=None</em>, <em>current_app=None</em><span class="optional">]</span>)<a class="headerlink" href="#django.core.urlresolvers.reverse" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p><tt class="docutils literal"><span class="pre">viewname</span></tt> is either the function name (either a function reference, or the string version of the name, if you used that form in <tt class="docutils literal"><span class="pre">urlpatterns</span></tt>) or the <a class="reference internal" href="#id2">URL pattern name</a>. Normally, you won’t need to worry about the <tt class="docutils literal"><span class="pre">urlconf</span></tt> parameter and will only pass in the positional and keyword arguments to use in the URL matching. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.core.urlresolvers</span> <span class="kn">import</span> <span class="n">reverse</span> <span class="k">def</span> <span class="nf">myview</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="k">return</span> <span class="n">HttpResponseRedirect</span><span class="p">(</span><span class="n">reverse</span><span class="p">(</span><span class="s">'arch-summary'</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">[</span><span class="mi">1945</span><span class="p">]))</span> </pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">reverse()</span></tt> function can reverse a large variety of regular expression patterns for URLs, but not every possible one. The main restriction at the moment is that the pattern cannot contain alternative choices using the vertical bar (<tt class="docutils literal"><span class="pre">"|"</span></tt>) character. You can quite happily use such patterns for matching against incoming URLs and sending them off to views, but you cannot reverse such patterns.</p> <p>The <tt class="docutils literal"><span class="pre">current_app</span></tt> argument allows you to provide a hint to the resolver indicating the application to which the currently executing view belongs. This <tt class="docutils literal"><span class="pre">current_app</span></tt> argument is used as a hint to resolve application namespaces into URLs on specific application instances, according to the <a class="reference internal" href="#topics-http-reversing-url-namespaces"><em>namespaced URL resolution strategy</em></a>.</p> <p>You can use <tt class="docutils literal"><span class="pre">kwargs</span></tt> instead of <tt class="docutils literal"><span class="pre">args</span></tt>. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">reverse</span><span class="p">(</span><span class="s">'admin:app_list'</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="p">{</span><span class="s">'app_label'</span><span class="p">:</span> <span class="s">'auth'</span><span class="p">})</span> <span class="go">'/admin/auth/'</span> </pre></div> </div> <p><tt class="docutils literal"><span class="pre">args</span></tt> and <tt class="docutils literal"><span class="pre">kwargs</span></tt> cannot be passed to <tt class="docutils literal"><span class="pre">reverse()</span></tt> at the same time.</p> <div class="admonition-make-sure-your-views-are-all-correct admonition"> <p class="first admonition-title">Make sure your views are all correct.</p> <p>As part of working out which URL names map to which patterns, the <tt class="docutils literal"><span class="pre">reverse()</span></tt> function has to import all of your URLconf files and examine the name of each view. This involves importing each view function. If there are <em>any</em> errors whilst importing any of your view functions, it will cause <tt class="docutils literal"><span class="pre">reverse()</span></tt> to raise an error, even if that view function is not the one you are trying to reverse.</p> <p class="last">Make sure that any views you reference in your URLconf files exist and can be imported correctly. Do not include lines that reference views you haven’t written yet, because those views will not be importable.</p> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>The string returned by <a class="reference internal" href="#django.core.urlresolvers.reverse" title="django.core.urlresolvers.reverse"><tt class="xref py py-meth docutils literal"><span class="pre">reverse()</span></tt></a> is already <a class="reference internal" href="../../ref/unicode.html#uri-and-iri-handling"><em>urlquoted</em></a>. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">reverse</span><span class="p">(</span><span class="s">'cities'</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">[</span><span class="s">u'Orléans'</span><span class="p">])</span> <span class="go">'.../Orl%C3%A9ans/'</span> </pre></div> </div> <p class="last">Applying further encoding (such as <a class="reference internal" href="../../ref/utils.html#django.utils.http.urlquote" title="django.utils.http.urlquote"><tt class="xref py py-meth docutils literal"><span class="pre">urlquote()</span></tt></a> or <tt class="docutils literal"><span class="pre">urllib.quote</span></tt>) to the output of <a class="reference internal" href="#django.core.urlresolvers.reverse" title="django.core.urlresolvers.reverse"><tt class="xref py py-meth docutils literal"><span class="pre">reverse()</span></tt></a> may produce undesirable results.</p> </div> </div> <div class="section" id="s-reverse-lazy"> <span id="reverse-lazy"></span><h3>reverse_lazy()<a class="headerlink" href="#reverse-lazy" title="Permalink to this headline">¶</a></h3> <div class="versionadded"> <span class="title">New in Django 1.4:</span> <a class="reference internal" href="../../releases/1.4.html"><em>Please see the release notes</em></a></div> <p>A lazily evaluated version of <a class="reference internal" href="#reverse">reverse()</a>.</p> <dl class="function"> <dt id="django.core.urlresolvers.reverse_lazy"> <tt class="descname">reverse_lazy</tt>(<em>viewname</em><span class="optional">[</span>, <em>urlconf=None</em>, <em>args=None</em>, <em>kwargs=None</em>, <em>current_app=None</em><span class="optional">]</span>)<a class="headerlink" href="#django.core.urlresolvers.reverse_lazy" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>It is useful for when you need to use a URL reversal before your project’s URLConf is loaded. Some common cases where this function is necessary are:</p> <ul class="simple"> <li>providing a reversed URL as the <tt class="docutils literal"><span class="pre">url</span></tt> attribute of a generic class-based view.</li> <li>providing a reversed URL to a decorator (such as the <tt class="docutils literal"><span class="pre">login_url</span></tt> argument for the <a class="reference internal" href="../auth.html#django.contrib.auth.decorators.permission_required" title="django.contrib.auth.decorators.permission_required"><tt class="xref py py-func docutils literal"><span class="pre">django.contrib.auth.decorators.permission_required()</span></tt></a> decorator).</li> <li>providing a reversed URL as a default value for a parameter in a function’s signature.</li> </ul> </div> <div class="section" id="s-resolve"> <span id="resolve"></span><h3>resolve()<a class="headerlink" href="#resolve" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="#django.core.urlresolvers.resolve" title="django.core.urlresolvers.resolve"><tt class="xref py py-func docutils literal"><span class="pre">django.core.urlresolvers.resolve()</span></tt></a> function can be used for resolving URL paths to the corresponding view functions. It has the following signature:</p> <dl class="function"> <dt id="django.core.urlresolvers.resolve"> <tt class="descname">resolve</tt>(<em>path</em>, <em>urlconf=None</em>)<a class="headerlink" href="#django.core.urlresolvers.resolve" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p><tt class="docutils literal"><span class="pre">path</span></tt> is the URL path you want to resolve. As with <a class="reference internal" href="#django.core.urlresolvers.reverse" title="django.core.urlresolvers.reverse"><tt class="xref py py-func docutils literal"><span class="pre">reverse()</span></tt></a>, you don’t need to worry about the <tt class="docutils literal"><span class="pre">urlconf</span></tt> parameter. The function returns a <a class="reference internal" href="#django.core.urlresolvers.ResolverMatch" title="django.core.urlresolvers.ResolverMatch"><tt class="xref py py-class docutils literal"><span class="pre">ResolverMatch</span></tt></a> object that allows you to access various meta-data about the resolved URL.</p> <p>If the URL does not resolve, the function raises an <a class="reference internal" href="views.html#django.http.Http404" title="django.http.Http404"><tt class="xref py py-class docutils literal"><span class="pre">Http404</span></tt></a> exception.</p> <dl class="class"> <dt id="django.core.urlresolvers.ResolverMatch"> <em class="property">class </em><tt class="descname">ResolverMatch</tt><a class="headerlink" href="#django.core.urlresolvers.ResolverMatch" title="Permalink to this definition">¶</a></dt> <dd><dl class="attribute"> <dt id="django.core.urlresolvers.ResolverMatch.func"> <tt class="descname">func</tt><a class="headerlink" href="#django.core.urlresolvers.ResolverMatch.func" title="Permalink to this definition">¶</a></dt> <dd><p>The view function that would be used to serve the URL</p> </dd></dl> <dl class="attribute"> <dt id="django.core.urlresolvers.ResolverMatch.args"> <tt class="descname">args</tt><a class="headerlink" href="#django.core.urlresolvers.ResolverMatch.args" title="Permalink to this definition">¶</a></dt> <dd><p>The arguments that would be passed to the view function, as parsed from the URL.</p> </dd></dl> <dl class="attribute"> <dt id="django.core.urlresolvers.ResolverMatch.kwargs"> <tt class="descname">kwargs</tt><a class="headerlink" href="#django.core.urlresolvers.ResolverMatch.kwargs" title="Permalink to this definition">¶</a></dt> <dd><p>The keyword arguments that would be passed to the view function, as parsed from the URL.</p> </dd></dl> <dl class="attribute"> <dt id="django.core.urlresolvers.ResolverMatch.url_name"> <tt class="descname">url_name</tt><a class="headerlink" href="#django.core.urlresolvers.ResolverMatch.url_name" title="Permalink to this definition">¶</a></dt> <dd><p>The name of the URL pattern that matches the URL.</p> </dd></dl> <dl class="attribute"> <dt id="django.core.urlresolvers.ResolverMatch.app_name"> <tt class="descname">app_name</tt><a class="headerlink" href="#django.core.urlresolvers.ResolverMatch.app_name" title="Permalink to this definition">¶</a></dt> <dd><p>The application namespace for the URL pattern that matches the URL.</p> </dd></dl> <dl class="attribute"> <dt id="django.core.urlresolvers.ResolverMatch.namespace"> <tt class="descname">namespace</tt><a class="headerlink" href="#django.core.urlresolvers.ResolverMatch.namespace" title="Permalink to this definition">¶</a></dt> <dd><p>The instance namespace for the URL pattern that matches the URL.</p> </dd></dl> <dl class="attribute"> <dt id="django.core.urlresolvers.ResolverMatch.namespaces"> <tt class="descname">namespaces</tt><a class="headerlink" href="#django.core.urlresolvers.ResolverMatch.namespaces" title="Permalink to this definition">¶</a></dt> <dd><p>The list of individual namespace components in the full instance namespace for the URL pattern that matches the URL. i.e., if the namespace is <tt class="docutils literal"><span class="pre">foo:bar</span></tt>, then namespaces will be <tt class="docutils literal"><span class="pre">['foo',</span> <span class="pre">'bar']</span></tt>.</p> </dd></dl> </dd></dl> <p>A <a class="reference internal" href="#django.core.urlresolvers.ResolverMatch" title="django.core.urlresolvers.ResolverMatch"><tt class="xref py py-class docutils literal"><span class="pre">ResolverMatch</span></tt></a> object can then be interrogated to provide information about the URL pattern that matches a URL:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># Resolve a URL</span> <span class="n">match</span> <span class="o">=</span> <span class="n">resolve</span><span class="p">(</span><span class="s">'/some/path/'</span><span class="p">)</span> <span class="c"># Print the URL pattern that matches the URL</span> <span class="k">print</span> <span class="n">match</span><span class="o">.</span><span class="n">url_name</span> </pre></div> </div> <p>A <a class="reference internal" href="#django.core.urlresolvers.ResolverMatch" title="django.core.urlresolvers.ResolverMatch"><tt class="xref py py-class docutils literal"><span class="pre">ResolverMatch</span></tt></a> object can also be assigned to a triple:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">func</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="n">resolve</span><span class="p">(</span><span class="s">'/some/path/'</span><span class="p">)</span> </pre></div> </div> <div class="versionchanged"> <span class="title">Changed in Django 1.3:</span> Triple-assignment exists for backwards-compatibility. Prior to Django 1.3, <a class="reference internal" href="#django.core.urlresolvers.resolve" title="django.core.urlresolvers.resolve"><tt class="xref py py-func docutils literal"><span class="pre">resolve()</span></tt></a> returned a triple containing (view function, arguments, keyword arguments); the <a class="reference internal" href="#django.core.urlresolvers.ResolverMatch" title="django.core.urlresolvers.ResolverMatch"><tt class="xref py py-class docutils literal"><span class="pre">ResolverMatch</span></tt></a> object (as well as the namespace and pattern information it provides) is not available in earlier Django releases.</div> <p>One possible use of <a class="reference internal" href="#django.core.urlresolvers.resolve" title="django.core.urlresolvers.resolve"><tt class="xref py py-func docutils literal"><span class="pre">resolve()</span></tt></a> would be to test whether a view would raise a <tt class="docutils literal"><span class="pre">Http404</span></tt> error before redirecting to it:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">urlparse</span> <span class="kn">import</span> <span class="n">urlparse</span> <span class="kn">from</span> <span class="nn">django.core.urlresolvers</span> <span class="kn">import</span> <span class="n">resolve</span> <span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponseRedirect</span><span class="p">,</span> <span class="n">Http404</span> <span class="k">def</span> <span class="nf">myview</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="nb">next</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'HTTP_REFERER'</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span> <span class="ow">or</span> <span class="s">'/'</span> <span class="n">response</span> <span class="o">=</span> <span class="n">HttpResponseRedirect</span><span class="p">(</span><span class="nb">next</span><span class="p">)</span> <span class="c"># modify the request and response as required, e.g. change locale</span> <span class="c"># and set corresponding locale cookie</span> <span class="n">view</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="n">resolve</span><span class="p">(</span><span class="n">urlparse</span><span class="p">(</span><span class="nb">next</span><span class="p">)[</span><span class="mi">2</span><span class="p">])</span> <span class="n">kwargs</span><span class="p">[</span><span class="s">'request'</span><span class="p">]</span> <span class="o">=</span> <span class="n">request</span> <span class="k">try</span><span class="p">:</span> <span class="n">view</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="k">except</span> <span class="n">Http404</span><span class="p">:</span> <span class="k">return</span> <span class="n">HttpResponseRedirect</span><span class="p">(</span><span class="s">'/'</span><span class="p">)</span> <span class="k">return</span> <span class="n">response</span> </pre></div> </div> </div> <div class="section" id="s-permalink"> <span id="permalink"></span><h3>permalink()<a class="headerlink" href="#permalink" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="../../ref/models/instances.html#django.db.models.permalink" title="django.db.models.permalink"><tt class="xref py py-func docutils literal"><span class="pre">django.db.models.permalink()</span></tt></a> decorator is useful for writing short methods that return a full URL path. For example, a model’s <tt class="docutils literal"><span class="pre">get_absolute_url()</span></tt> method. See <a class="reference internal" href="../../ref/models/instances.html#django.db.models.permalink" title="django.db.models.permalink"><tt class="xref py py-func docutils literal"><span class="pre">django.db.models.permalink()</span></tt></a> for more.</p> </div> <div class="section" id="s-get-script-prefix"> <span id="get-script-prefix"></span><h3>get_script_prefix()<a class="headerlink" href="#get-script-prefix" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="django.core.urlresolvers.get_script_prefix"> <tt class="descname">get_script_prefix</tt>()<a class="headerlink" href="#django.core.urlresolvers.get_script_prefix" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Normally, you should always use <a class="reference internal" href="#django.core.urlresolvers.reverse" title="django.core.urlresolvers.reverse"><tt class="xref py py-func docutils literal"><span class="pre">reverse()</span></tt></a> or <a class="reference internal" href="../../ref/models/instances.html#django.db.models.permalink" title="django.db.models.permalink"><tt class="xref py py-func docutils literal"><span class="pre">permalink()</span></tt></a> to define URLs within your application. However, if your application constructs part of the URL hierarchy itself, you may occasionally need to generate URLs. In that case, you need to be able to find the base URL of the Django project within its Web server (normally, <a class="reference internal" href="#django.core.urlresolvers.reverse" title="django.core.urlresolvers.reverse"><tt class="xref py py-func docutils literal"><span class="pre">reverse()</span></tt></a> takes care of this for you). In that case, you can call <tt class="docutils literal"><span class="pre">get_script_prefix()</span></tt>, which will return the script prefix portion of the URL for your Django project. If your Django project is at the root of its Web server, this is always <tt class="docutils literal"><span class="pre">"/"</span></tt>, but it can be changed, for instance by using <tt class="docutils literal"><span class="pre">django.root</span></tt> (see <a class="reference internal" href="../../howto/deployment/modpython.html"><em>How to use Django with Apache and mod_python</em></a>).</p> </div> </div> </div> </div> </div> </div> <div class="yui-b" id="sidebar"> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3><a href="../../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">URL dispatcher</a><ul> <li><a class="reference internal" href="#overview">Overview</a></li> <li><a class="reference internal" href="#how-django-processes-a-request">How Django processes a request</a></li> <li><a class="reference internal" href="#example">Example</a></li> <li><a class="reference internal" href="#named-groups">Named groups</a><ul> <li><a class="reference internal" href="#the-matching-grouping-algorithm">The matching/grouping algorithm</a></li> </ul> </li> <li><a class="reference internal" href="#what-the-urlconf-searches-against">What the URLconf searches against</a></li> <li><a class="reference internal" href="#syntax-of-the-urlpatterns-variable">Syntax of the urlpatterns variable</a></li> <li><a class="reference internal" href="#module-django.conf.urls"><tt class="docutils literal"><span class="pre">django.conf.urls</span></tt> utility functions</a><ul> <li><a class="reference internal" href="#patterns">patterns</a></li> <li><a class="reference internal" href="#url">url</a></li> <li><a class="reference internal" href="#include">include</a></li> </ul> </li> <li><a class="reference internal" href="#error-handling">Error handling</a><ul> <li><a class="reference internal" href="#handler403">handler403</a></li> <li><a class="reference internal" href="#handler404">handler404</a></li> <li><a class="reference internal" href="#handler500">handler500</a></li> </ul> </li> <li><a class="reference internal" href="#notes-on-capturing-text-in-urls">Notes on capturing text in URLs</a></li> <li><a class="reference internal" href="#performance">Performance</a></li> <li><a class="reference internal" href="#the-view-prefix">The view prefix</a><ul> <li><a class="reference internal" href="#multiple-view-prefixes">Multiple view prefixes</a></li> </ul> </li> <li><a class="reference internal" href="#including-other-urlconfs">Including other URLconfs</a><ul> <li><a class="reference internal" href="#captured-parameters">Captured parameters</a></li> <li><a class="reference internal" href="#defining-url-namespaces">Defining URL namespaces</a></li> </ul> </li> <li><a class="reference internal" href="#passing-extra-options-to-view-functions">Passing extra options to view functions</a><ul> <li><a class="reference internal" href="#passing-extra-options-to-include">Passing extra options to <tt class="docutils literal"><span class="pre">include()</span></tt></a></li> </ul> </li> <li><a class="reference internal" href="#passing-callable-objects-instead-of-strings">Passing callable objects instead of strings</a></li> <li><a class="reference internal" href="#naming-url-patterns">Naming URL patterns</a><ul> <li><a class="reference internal" href="#url-namespaces">URL namespaces</a></li> </ul> </li> <li><a class="reference internal" href="#django-core-urlresolvers-utility-functions"><tt class="docutils literal"><span class="pre">django.core.urlresolvers</span></tt> utility functions</a><ul> <li><a class="reference internal" href="#reverse">reverse()</a></li> <li><a class="reference internal" href="#reverse-lazy">reverse_lazy()</a></li> <li><a class="reference internal" href="#resolve">resolve()</a></li> <li><a class="reference internal" href="#permalink">permalink()</a></li> <li><a class="reference internal" href="#get-script-prefix">get_script_prefix()</a></li> </ul> </li> </ul> </li> </ul> <h3>Browse</h3> <ul> <li>Prev: <a href="index.html">Handling HTTP requests</a></li> <li>Next: <a href="views.html">Writing views</a></li> </ul> <h3>You are here:</h3> <ul> <li> <a href="../../index.html">Django 1.4.21 documentation</a> <ul><li><a href="../index.html">Using Django</a> <ul><li><a href="index.html">Handling HTTP requests</a> <ul><li>URL dispatcher</li></ul> </li></ul></li></ul> </li> </ul> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../_sources/topics/http/urls.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <h3>Last update:</h3> <p class="topless">Jul 10, 2015</p> </div> </div> <div id="ft"> <div class="nav"> « <a href="index.html" title="Handling HTTP requests">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="views.html" title="Writing views">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>