Sophie

Sophie

distrib > Fedora > 20 > i386 > by-pkgid > 422242acff54b9373d7d4b7f73232ce1 > files > 664

python3-django-doc-1.6.7-1.fc20.noarch.rpm


<!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>The Django template language: For Python programmers &mdash; Django 1.6.7 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.6.7',
        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.6.7 documentation" href="../../index.html" />
    <link rel="up" title="Templates" href="index.html" />
    <link rel="next" title="Unicode data" href="../unicode.html" />
    <link rel="prev" title="Built-in template tags and filters" href="builtins.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 = "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.6.7 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">
    &laquo; <a href="builtins.html" title="Built-in template tags and filters">previous</a> 
     |
    <a href="../index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="../unicode.html" title="Unicode data">next</a> &raquo;</div>
    </div>
    
    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-templates-api">
            
  <div class="section" id="s-module-django.template">
<span id="s-the-django-template-language-for-python-programmers"></span><span id="module-django.template"></span><span id="the-django-template-language-for-python-programmers"></span><h1>The Django template language: For Python programmers<a class="headerlink" href="#module-django.template" title="Permalink to this headline">¶</a></h1>
<p>This document explains the Django template system from a technical
perspective &#8211; how it works and how to extend it. If you&#8217;re just looking for
reference on the language syntax, see <a class="reference internal" href="../../topics/templates.html"><em>The Django template language</em></a>.</p>
<p>If you&#8217;re looking to use the Django template system as part of another
application &#8211; i.e., without the rest of the framework &#8211; make sure to read
the <a class="reference internal" href="#configuring-the-template-system-in-standalone-mode">configuration</a> section later in this document.</p>
<div class="section" id="s-basics">
<span id="basics"></span><h2>Basics<a class="headerlink" href="#basics" title="Permalink to this headline">¶</a></h2>
<p>A <strong>template</strong> is a text document, or a normal Python string, that is marked-up
using the Django template language. A template can contain <strong>block tags</strong> or
<strong>variables</strong>.</p>
<p>A <strong>block tag</strong> is a symbol within a template that does something.</p>
<p>This definition is deliberately vague. For example, a block tag can output
content, serve as a control structure (an &#8220;if&#8221; statement or &#8220;for&#8221; loop), grab
content from a database or enable access to other template tags.</p>
<p>Block tags are surrounded by <tt class="docutils literal"><span class="pre">&quot;{%&quot;</span></tt> and <tt class="docutils literal"><span class="pre">&quot;%}&quot;</span></tt>.</p>
<p>Example template with block tags:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">if</span> <span class="nv">is_logged_in</span> <span class="cp">%}</span>Thanks for logging in!<span class="cp">{%</span> <span class="k">else</span> <span class="cp">%}</span>Please log in.<span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>A <strong>variable</strong> is a symbol within a template that outputs a value.</p>
<p>Variable tags are surrounded by <tt class="docutils literal"><span class="pre">&quot;{{&quot;</span></tt> and <tt class="docutils literal"><span class="pre">&quot;}}&quot;</span></tt>.</p>
<p>Example template with variables:</p>
<div class="highlight-html+django"><div class="highlight"><pre>My first name is <span class="cp">{{</span> <span class="nv">first_name</span> <span class="cp">}}</span>. My last name is <span class="cp">{{</span> <span class="nv">last_name</span> <span class="cp">}}</span>.
</pre></div>
</div>
<p>A <strong>context</strong> is a &#8220;variable name&#8221; -&gt; &#8220;variable value&#8221; mapping that is passed
to a template.</p>
<p>A template <strong>renders</strong> a context by replacing the variable &#8220;holes&#8221; with values
from the context and executing all block tags.</p>
</div>
<div class="section" id="s-using-the-template-system">
<span id="using-the-template-system"></span><h2>Using the template system<a class="headerlink" href="#using-the-template-system" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="django.template.Template">
<em class="property">class </em><tt class="descname">Template</tt><a class="headerlink" href="#django.template.Template" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Using the template system in Python is a two-step process:</p>
<ul class="simple">
<li>First, you compile the raw template code into a <tt class="docutils literal"><span class="pre">Template</span></tt> object.</li>
<li>Then, you call the <tt class="docutils literal"><span class="pre">render()</span></tt> method of the <tt class="docutils literal"><span class="pre">Template</span></tt> object with a
given context.</li>
</ul>
<div class="section" id="s-compiling-a-string">
<span id="compiling-a-string"></span><h3>Compiling a string<a class="headerlink" href="#compiling-a-string" title="Permalink to this headline">¶</a></h3>
<p>The easiest way to create a <tt class="docutils literal"><span class="pre">Template</span></tt> object is by instantiating it
directly. The class lives at <a class="reference internal" href="#django.template.Template" title="django.template.Template"><tt class="xref py py-class docutils literal"><span class="pre">django.template.Template</span></tt></a>. The constructor
takes one argument &#8211; the raw template code:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">Template</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;My name is {{ my_name }}.&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">&lt;django.template.Template instance&gt;</span>
</pre></div>
</div>
<div class="admonition-behind-the-scenes admonition">
<p class="first admonition-title">Behind the scenes</p>
<p>The system only parses your raw template code once &#8211; when you create the
<tt class="docutils literal"><span class="pre">Template</span></tt> object. From then on, it&#8217;s stored internally as a &#8220;node&#8221;
structure for performance.</p>
<p class="last">Even the parsing itself is quite fast. Most of the parsing happens via a
single call to a single, short, regular expression.</p>
</div>
</div>
<div class="section" id="s-rendering-a-context">
<span id="rendering-a-context"></span><h3>Rendering a context<a class="headerlink" href="#rendering-a-context" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="django.template.render">
<tt class="descname">render</tt>(<em>context</em>)<a class="headerlink" href="#django.template.render" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Once you have a compiled <tt class="docutils literal"><span class="pre">Template</span></tt> object, you can render a context &#8211; or
multiple contexts &#8211; with it. The <tt class="docutils literal"><span class="pre">Context</span></tt> class lives at
<a class="reference internal" href="#django.template.Context" title="django.template.Context"><tt class="xref py py-class docutils literal"><span class="pre">django.template.Context</span></tt></a>, and the constructor takes two (optional)
arguments:</p>
<ul class="simple">
<li>A dictionary mapping variable names to variable values.</li>
<li>The name of the current application. This application name is used
to help <a class="reference internal" href="../../topics/http/urls.html#topics-http-reversing-url-namespaces"><em>resolve namespaced URLs</em></a>.
If you&#8217;re not using namespaced URLs, you can ignore this argument.</li>
</ul>
<p>Call the <tt class="docutils literal"><span class="pre">Template</span></tt> object&#8217;s <tt class="docutils literal"><span class="pre">render()</span></tt> method with the context to &#8220;fill&#8221; the
template:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">Context</span><span class="p">,</span> <span class="n">Template</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;My name is {{ my_name }}.&quot;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Context</span><span class="p">({</span><span class="s">&quot;my_name&quot;</span><span class="p">:</span> <span class="s">&quot;Adrian&quot;</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="go">&quot;My name is Adrian.&quot;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Context</span><span class="p">({</span><span class="s">&quot;my_name&quot;</span><span class="p">:</span> <span class="s">&quot;Dolores&quot;</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="go">&quot;My name is Dolores.&quot;</span>
</pre></div>
</div>
<div class="section" id="s-variables-and-lookups">
<span id="variables-and-lookups"></span><h4>Variables and lookups<a class="headerlink" href="#variables-and-lookups" title="Permalink to this headline">¶</a></h4>
<p>Variable names must consist of any letter (A-Z), any digit (0-9), an underscore
(but they must not start with an underscore) or a dot.</p>
<p>Dots have a special meaning in template rendering. A dot in a variable name
signifies a <strong>lookup</strong>. Specifically, when the template system encounters a
dot in a variable name, it tries the following lookups, in this order:</p>
<ul class="simple">
<li>Dictionary lookup. Example: <tt class="docutils literal"><span class="pre">foo[&quot;bar&quot;]</span></tt></li>
<li>Attribute lookup. Example: <tt class="docutils literal"><span class="pre">foo.bar</span></tt></li>
<li>List-index lookup. Example: <tt class="docutils literal"><span class="pre">foo[bar]</span></tt></li>
</ul>
<p>Note that &#8220;bar&#8221; in a template expression like <tt class="docutils literal"><span class="pre">{{</span> <span class="pre">foo.bar</span> <span class="pre">}}</span></tt> will be
interpreted as a literal string and not using the value of the variable &#8220;bar&#8221;,
if one exists in the template context.</p>
<p>The template system uses the first lookup type that works. It&#8217;s short-circuit
logic. Here are a few examples:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">Context</span><span class="p">,</span> <span class="n">Template</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;My name is {{ person.first_name }}.&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s">&quot;person&quot;</span><span class="p">:</span> <span class="p">{</span><span class="s">&quot;first_name&quot;</span><span class="p">:</span> <span class="s">&quot;Joe&quot;</span><span class="p">,</span> <span class="s">&quot;last_name&quot;</span><span class="p">:</span> <span class="s">&quot;Johnson&quot;</span><span class="p">}}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">Context</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>
<span class="go">&quot;My name is Joe.&quot;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">PersonClass</span><span class="p">:</span> <span class="k">pass</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">PersonClass</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">first_name</span> <span class="o">=</span> <span class="s">&quot;Ron&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">last_name</span> <span class="o">=</span> <span class="s">&quot;Nasty&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">Context</span><span class="p">({</span><span class="s">&quot;person&quot;</span><span class="p">:</span> <span class="n">p</span><span class="p">}))</span>
<span class="go">&quot;My name is Ron.&quot;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;The first stooge in the list is {{ stooges.0 }}.&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Context</span><span class="p">({</span><span class="s">&quot;stooges&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s">&quot;Larry&quot;</span><span class="p">,</span> <span class="s">&quot;Curly&quot;</span><span class="p">,</span> <span class="s">&quot;Moe&quot;</span><span class="p">]})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="go">&quot;The first stooge in the list is Larry.&quot;</span>
</pre></div>
</div>
<p>If any part of the variable is callable, the template system will try calling
it. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">PersonClass2</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">name</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s">&quot;Samantha&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;My name is {{ person.name }}.&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">Context</span><span class="p">({</span><span class="s">&quot;person&quot;</span><span class="p">:</span> <span class="n">PersonClass2</span><span class="p">}))</span>
<span class="go">&quot;My name is Samantha.&quot;</span>
</pre></div>
</div>
<p>Callable variables are slightly more complex than variables which only require
straight lookups. Here are some things to keep in mind:</p>
<ul>
<li><p class="first">If the variable raises an exception when called, the exception will be
propagated, unless the exception has an attribute
<tt class="docutils literal"><span class="pre">silent_variable_failure</span></tt> whose value is <tt class="docutils literal"><span class="pre">True</span></tt>. If the exception
<em>does</em> have a <tt class="docutils literal"><span class="pre">silent_variable_failure</span></tt> attribute whose value is
<tt class="docutils literal"><span class="pre">True</span></tt>, the variable will render as an empty string. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;My name is {{ person.first_name }}.&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">PersonClass3</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">first_name</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">raise</span> <span class="ne">AssertionError</span><span class="p">(</span><span class="s">&quot;foo&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">PersonClass3</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">Context</span><span class="p">({</span><span class="s">&quot;person&quot;</span><span class="p">:</span> <span class="n">p</span><span class="p">}))</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">AssertionError</span>: <span class="n">foo</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">SilentAssertionError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">silent_variable_failure</span> <span class="o">=</span> <span class="bp">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">PersonClass4</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">first_name</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">raise</span> <span class="n">SilentAssertionError</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">PersonClass4</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">Context</span><span class="p">({</span><span class="s">&quot;person&quot;</span><span class="p">:</span> <span class="n">p</span><span class="p">}))</span>
<span class="go">&quot;My name is .&quot;</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="../exceptions.html#django.core.exceptions.ObjectDoesNotExist" title="django.core.exceptions.ObjectDoesNotExist"><tt class="xref py py-exc docutils literal"><span class="pre">django.core.exceptions.ObjectDoesNotExist</span></tt></a>, which is the
base class for all Django database API <tt class="docutils literal"><span class="pre">DoesNotExist</span></tt> exceptions, has
<tt class="docutils literal"><span class="pre">silent_variable_failure</span> <span class="pre">=</span> <span class="pre">True</span></tt>. So if you&#8217;re using Django templates
with Django model objects, any <tt class="docutils literal"><span class="pre">DoesNotExist</span></tt> exception will fail
silently.</p>
</li>
<li><p class="first">A variable can only be called if it has no required arguments. Otherwise,
the system will return an empty string.</p>
</li>
</ul>
<ul id="alters-data-description">
<li><p class="first">Obviously, there can be side effects when calling some variables, and
it&#8217;d be either foolish or a security hole to allow the template system
to access them.</p>
<p>A good example is the <a class="reference internal" href="../models/instances.html#django.db.models.Model.delete" title="django.db.models.Model.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a> method on
each Django model object. The template system shouldn&#8217;t be allowed to do
something like this:</p>
<div class="highlight-python"><pre>I will now delete this valuable data. {{ data.delete }}</pre>
</div>
<p>To prevent this, set an <tt class="docutils literal"><span class="pre">alters_data</span></tt> attribute on the callable
variable. The template system won&#8217;t call a variable if it has
<tt class="docutils literal"><span class="pre">alters_data=True</span></tt> set, and will instead replace the variable with
<a class="reference internal" href="../settings.html#std:setting-TEMPLATE_STRING_IF_INVALID"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_STRING_IF_INVALID</span></tt></a>, unconditionally.  The
dynamically-generated <a class="reference internal" href="../models/instances.html#django.db.models.Model.delete" title="django.db.models.Model.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a> and
<a class="reference internal" href="../models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a> methods on Django model objects get
<tt class="docutils literal"><span class="pre">alters_data=True</span></tt> automatically. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">sensitive_function</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">database_record</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="n">sensitive_function</span><span class="o">.</span><span class="n">alters_data</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
</li>
<li><p class="first">Occasionally you may want to turn off this feature for other reasons,
and tell the template system to leave a variable un-called no matter
what.  To do so, set a <tt class="docutils literal"><span class="pre">do_not_call_in_templates</span></tt> attribute on the
callable with the value <tt class="docutils literal"><span class="pre">True</span></tt>.  The template system then will act as
if your variable is not callable (allowing you to access attributes of
the callable, for example).</p>
</li>
</ul>
</div>
<div class="section" id="s-how-invalid-variables-are-handled">
<span id="s-invalid-template-variables"></span><span id="how-invalid-variables-are-handled"></span><span id="invalid-template-variables"></span><h4>How invalid variables are handled<a class="headerlink" href="#how-invalid-variables-are-handled" title="Permalink to this headline">¶</a></h4>
<p>Generally, if a variable doesn&#8217;t exist, the template system inserts the
value of the <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_STRING_IF_INVALID"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_STRING_IF_INVALID</span></tt></a> setting, which is set to
<tt class="docutils literal"><span class="pre">''</span></tt> (the empty string) by default.</p>
<p>Filters that are applied to an invalid variable will only be applied if
<a class="reference internal" href="../settings.html#std:setting-TEMPLATE_STRING_IF_INVALID"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_STRING_IF_INVALID</span></tt></a> is set to <tt class="docutils literal"><span class="pre">''</span></tt> (the empty string). If
<a class="reference internal" href="../settings.html#std:setting-TEMPLATE_STRING_IF_INVALID"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_STRING_IF_INVALID</span></tt></a> is set to any other value, variable
filters will be ignored.</p>
<p>This behavior is slightly different for the <tt class="docutils literal"><span class="pre">if</span></tt>, <tt class="docutils literal"><span class="pre">for</span></tt> and <tt class="docutils literal"><span class="pre">regroup</span></tt>
template tags. If an invalid variable is provided to one of these template
tags, the variable will be interpreted as <tt class="docutils literal"><span class="pre">None</span></tt>. Filters are always
applied to invalid variables within these template tags.</p>
<p>If <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_STRING_IF_INVALID"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_STRING_IF_INVALID</span></tt></a> contains a <tt class="docutils literal"><span class="pre">'%s'</span></tt>, the format marker will
be replaced with the name of the invalid variable.</p>
<div class="admonition-for-debug-purposes-only admonition">
<p class="first admonition-title">For debug purposes only!</p>
<p>While <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_STRING_IF_INVALID"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_STRING_IF_INVALID</span></tt></a> can be a useful debugging tool,
it is a bad idea to turn it on as a &#8216;development default&#8217;.</p>
<p>Many templates, including those in the Admin site, rely upon the
silence of the template system when a non-existent variable is
encountered. If you assign a value other than <tt class="docutils literal"><span class="pre">''</span></tt> to
<a class="reference internal" href="../settings.html#std:setting-TEMPLATE_STRING_IF_INVALID"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_STRING_IF_INVALID</span></tt></a>, you will experience rendering
problems with these templates and sites.</p>
<p class="last">Generally, <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_STRING_IF_INVALID"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_STRING_IF_INVALID</span></tt></a> should only be enabled
in order to debug a specific template problem, then cleared
once debugging is complete.</p>
</div>
</div>
<div class="section" id="s-builtin-variables">
<span id="builtin-variables"></span><h4>Builtin variables<a class="headerlink" href="#builtin-variables" title="Permalink to this headline">¶</a></h4>
<p>Every context contains <tt class="docutils literal"><span class="pre">True</span></tt>, <tt class="docutils literal"><span class="pre">False</span></tt> and <tt class="docutils literal"><span class="pre">None</span></tt>. As you would expect,
these variables resolve to the corresponding Python objects.</p>
<div class="versionadded">
<span class="title">New in Django 1.5:</span> Before Django 1.5, these variables weren&#8217;t a special case, and they
resolved to <tt class="docutils literal"><span class="pre">None</span></tt> unless you defined them in the context.</div>
</div>
</div>
<div class="section" id="s-playing-with-context-objects">
<span id="playing-with-context-objects"></span><h3>Playing with Context objects<a class="headerlink" href="#playing-with-context-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.template.Context">
<em class="property">class </em><tt class="descname">Context</tt><a class="headerlink" href="#django.template.Context" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Most of the time, you&#8217;ll instantiate <tt class="docutils literal"><span class="pre">Context</span></tt> objects by passing in a
fully-populated dictionary to <tt class="docutils literal"><span class="pre">Context()</span></tt>. But you can add and delete items
from a <tt class="docutils literal"><span class="pre">Context</span></tt> object once it&#8217;s been instantiated, too, using standard
dictionary syntax:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">Context</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Context</span><span class="p">({</span><span class="s">&quot;foo&quot;</span><span class="p">:</span> <span class="s">&quot;bar&quot;</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span>
<span class="go">&#39;bar&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">c</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span>
<span class="go">&#39;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;newvariable&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;hello&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;newvariable&#39;</span><span class="p">]</span>
<span class="go">&#39;hello&#39;</span>
</pre></div>
</div>
<dl class="method">
<dt id="django.template.Context.pop">
<tt class="descclassname">Context.</tt><tt class="descname">pop</tt>()<a class="headerlink" href="#django.template.Context.pop" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="django.template.Context.push">
<tt class="descclassname">Context.</tt><tt class="descname">push</tt>()<a class="headerlink" href="#django.template.Context.push" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="exception">
<dt id="django.template.ContextPopException">
<em class="property">exception </em><tt class="descname">ContextPopException</tt><a class="headerlink" href="#django.template.ContextPopException" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A <tt class="docutils literal"><span class="pre">Context</span></tt> object is a stack. That is, you can <tt class="docutils literal"><span class="pre">push()</span></tt> and <tt class="docutils literal"><span class="pre">pop()</span></tt> it.
If you <tt class="docutils literal"><span class="pre">pop()</span></tt> too much, it&#8217;ll raise
<tt class="docutils literal"><span class="pre">django.template.ContextPopException</span></tt>:</p>
<div class="highlight-python"><pre>&gt;&gt;&gt; c = Context()
&gt;&gt;&gt; c['foo'] = 'first level'
&gt;&gt;&gt; c.push()
{}
&gt;&gt;&gt; c['foo'] = 'second level'
&gt;&gt;&gt; c['foo']
'second level'
&gt;&gt;&gt; c.pop()
{'foo': 'second level'}
&gt;&gt;&gt; c['foo']
'first level'
&gt;&gt;&gt; c['foo'] = 'overwritten'
&gt;&gt;&gt; c['foo']
'overwritten'
&gt;&gt;&gt; c.pop()
Traceback (most recent call last):
...
django.template.ContextPopException</pre>
</div>
<dl class="method">
<dt id="django.template.update">
<tt class="descname">update</tt>(<em>other_dict</em>)<a class="headerlink" href="#django.template.update" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>In addition to <tt class="docutils literal"><span class="pre">push()</span></tt> and <tt class="docutils literal"><span class="pre">pop()</span></tt>, the <tt class="docutils literal"><span class="pre">Context</span></tt>
object also defines an <tt class="docutils literal"><span class="pre">update()</span></tt> method. This works like <tt class="docutils literal"><span class="pre">push()</span></tt>
but takes a dictionary as an argument and pushes that dictionary onto
the stack instead of an empty one.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Context</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;first level&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">update</span><span class="p">({</span><span class="s">&#39;foo&#39;</span><span class="p">:</span> <span class="s">&#39;updated&#39;</span><span class="p">})</span>
<span class="go">{&#39;foo&#39;: &#39;updated&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span>
<span class="go">&#39;updated&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">{&#39;foo&#39;: &#39;updated&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span>
<span class="go">&#39;first level&#39;</span>
</pre></div>
</div>
<p>Using a <tt class="docutils literal"><span class="pre">Context</span></tt> as a stack comes in handy in some custom template tags, as
you&#8217;ll see below.</p>
</div>
<div class="section" id="s-subclassing-context-requestcontext">
<span id="s-id1"></span><span id="subclassing-context-requestcontext"></span><span id="id1"></span><h3>Subclassing Context: RequestContext<a class="headerlink" href="#subclassing-context-requestcontext" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.template.RequestContext">
<em class="property">class </em><tt class="descname">RequestContext</tt><a class="headerlink" href="#django.template.RequestContext" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Django comes with a special <tt class="docutils literal"><span class="pre">Context</span></tt> class,
<tt class="docutils literal"><span class="pre">django.template.RequestContext</span></tt>, that acts slightly differently than the
normal <tt class="docutils literal"><span class="pre">django.template.Context</span></tt>. The first difference is that it takes an
<a class="reference internal" href="../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. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">c</span> <span class="o">=</span> <span class="n">RequestContext</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="p">{</span>
    <span class="s">&#39;foo&#39;</span><span class="p">:</span> <span class="s">&#39;bar&#39;</span><span class="p">,</span>
<span class="p">})</span>
</pre></div>
</div>
<p>The second difference is that it automatically populates the context with a few
variables, according to your <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> setting.</p>
<p>The <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> setting is a tuple of callables &#8211;
called <strong>context processors</strong> &#8211; that take a request object as their argument
and return a dictionary of items to be merged into the context. By default,
<a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> is set to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">(</span><span class="s">&quot;django.contrib.auth.context_processors.auth&quot;</span><span class="p">,</span>
<span class="s">&quot;django.core.context_processors.debug&quot;</span><span class="p">,</span>
<span class="s">&quot;django.core.context_processors.i18n&quot;</span><span class="p">,</span>
<span class="s">&quot;django.core.context_processors.media&quot;</span><span class="p">,</span>
<span class="s">&quot;django.core.context_processors.static&quot;</span><span class="p">,</span>
<span class="s">&quot;django.core.context_processors.tz&quot;</span><span class="p">,</span>
<span class="s">&quot;django.contrib.messages.context_processors.messages&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>In addition to these, <tt class="docutils literal"><span class="pre">RequestContext</span></tt> always uses
<tt class="docutils literal"><span class="pre">django.core.context_processors.csrf</span></tt>.  This is a security
related context processor required by the admin and other contrib apps, and,
in case of accidental misconfiguration, it is deliberately hardcoded in and
cannot be turned off by the <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> setting.</p>
<p>Each processor is applied in order. That means, if one processor adds a
variable to the context and a second processor adds a variable with the same
name, the second will override the first. The default processors are explained
below.</p>
<div class="admonition-when-context-processors-are-applied admonition">
<p class="first admonition-title">When context processors are applied</p>
<p class="last">Context processors are applied <em>after</em> the context itself is processed.
This means that a context processor may overwrite variables you&#8217;ve
supplied to your <tt class="docutils literal"><span class="pre">Context</span></tt> or <tt class="docutils literal"><span class="pre">RequestContext</span></tt>, so take care
to avoid variable names that overlap with those supplied by your
context processors.</p>
</div>
<p>Also, you can give <tt class="docutils literal"><span class="pre">RequestContext</span></tt> a list of additional processors, using the
optional, third positional argument, <tt class="docutils literal"><span class="pre">processors</span></tt>. In this example, the
<tt class="docutils literal"><span class="pre">RequestContext</span></tt> instance gets a <tt class="docutils literal"><span class="pre">ip_address</span></tt> variable:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span>
<span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">RequestContext</span>

<span class="k">def</span> <span class="nf">ip_address_processor</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">{</span><span class="s">&#39;ip_address&#39;</span><span class="p">:</span> <span class="n">request</span><span class="o">.</span><span class="n">META</span><span class="p">[</span><span class="s">&#39;REMOTE_ADDR&#39;</span><span class="p">]}</span>

<span class="k">def</span> <span class="nf">some_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">c</span> <span class="o">=</span> <span class="n">RequestContext</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="p">{</span>
        <span class="s">&#39;foo&#39;</span><span class="p">:</span> <span class="s">&#39;bar&#39;</span><span class="p">,</span>
    <span class="p">},</span> <span class="p">[</span><span class="n">ip_address_processor</span><span class="p">])</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">c</span><span class="p">))</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>If you&#8217;re using Django&#8217;s <a class="reference internal" href="../../topics/http/shortcuts.html#django.shortcuts.render_to_response" title="django.shortcuts.render_to_response"><tt class="xref py py-func docutils literal"><span class="pre">render_to_response()</span></tt></a>
shortcut to populate a template with the contents of a dictionary, your
template will be passed a <tt class="docutils literal"><span class="pre">Context</span></tt> instance by default (not a
<tt class="docutils literal"><span class="pre">RequestContext</span></tt>). To use a <tt class="docutils literal"><span class="pre">RequestContext</span></tt> in your template
rendering, pass an optional third argument to
<a class="reference internal" href="../../topics/http/shortcuts.html#django.shortcuts.render_to_response" title="django.shortcuts.render_to_response"><tt class="xref py py-func docutils literal"><span class="pre">render_to_response()</span></tt></a>: a <tt class="docutils literal"><span class="pre">RequestContext</span></tt>
instance. Your code might look like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">render_to_response</span>
<span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">RequestContext</span>

<span class="k">def</span> <span class="nf">some_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">return</span> <span class="n">render_to_response</span><span class="p">(</span><span class="s">&#39;my_template.html&#39;</span><span class="p">,</span>
                              <span class="n">my_data_dictionary</span><span class="p">,</span>
                              <span class="n">context_instance</span><span class="o">=</span><span class="n">RequestContext</span><span class="p">(</span><span class="n">request</span><span class="p">))</span>
</pre></div>
</div>
<p>Alternatively, use the <a class="reference internal" href="../../topics/http/shortcuts.html#django.shortcuts.render" title="django.shortcuts.render"><tt class="xref py py-meth docutils literal"><span class="pre">render()</span></tt></a> shortcut which is
the same as a call to <a class="reference internal" href="../../topics/http/shortcuts.html#django.shortcuts.render_to_response" title="django.shortcuts.render_to_response"><tt class="xref py py-func docutils literal"><span class="pre">render_to_response()</span></tt></a> with a
context_instance argument that forces the use of a <tt class="docutils literal"><span class="pre">RequestContext</span></tt>.</p>
<p class="last">Note that the contents of a supplied dictionary (<tt class="docutils literal"><span class="pre">my_data_dictionary</span></tt>
in this example) will take precedence over any variables supplied by
context processors or the <tt class="docutils literal"><span class="pre">RequestContext</span></tt>.</p>
</div>
<p>Here&#8217;s what each of the default processors does:</p>
<div class="section" id="s-django-contrib-auth-context-processors-auth">
<span id="django-contrib-auth-context-processors-auth"></span><h4>django.contrib.auth.context_processors.auth<a class="headerlink" href="#django-contrib-auth-context-processors-auth" title="Permalink to this headline">¶</a></h4>
<p>If <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> contains this processor, every
<tt class="docutils literal"><span class="pre">RequestContext</span></tt> will contain these variables:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">user</span></tt> &#8211; An <tt class="docutils literal"><span class="pre">auth.User</span></tt> instance representing the currently
logged-in user (or an <tt class="docutils literal"><span class="pre">AnonymousUser</span></tt> instance, if the client isn&#8217;t
logged in).</li>
<li><tt class="docutils literal"><span class="pre">perms</span></tt> &#8211; An instance of
<tt class="docutils literal"><span class="pre">django.contrib.auth.context_processors.PermWrapper</span></tt>, representing the
permissions that the currently logged-in user has.</li>
</ul>
</div>
<div class="section" id="s-django-core-context-processors-debug">
<span id="django-core-context-processors-debug"></span><h4>django.core.context_processors.debug<a class="headerlink" href="#django-core-context-processors-debug" title="Permalink to this headline">¶</a></h4>
<p>If <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> contains this processor, every
<tt class="docutils literal"><span class="pre">RequestContext</span></tt> will contain these two variables &#8211; but only if your
<a class="reference internal" href="../settings.html#std:setting-DEBUG"><tt class="xref std std-setting docutils literal"><span class="pre">DEBUG</span></tt></a> setting is set to <tt class="docutils literal"><span class="pre">True</span></tt> and the request&#8217;s IP address
(<tt class="docutils literal"><span class="pre">request.META['REMOTE_ADDR']</span></tt>) is in the <a class="reference internal" href="../settings.html#std:setting-INTERNAL_IPS"><tt class="xref std std-setting docutils literal"><span class="pre">INTERNAL_IPS</span></tt></a> setting:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">debug</span></tt> &#8211; <tt class="docutils literal"><span class="pre">True</span></tt>. You can use this in templates to test whether
you&#8217;re in <a class="reference internal" href="../settings.html#std:setting-DEBUG"><tt class="xref std std-setting docutils literal"><span class="pre">DEBUG</span></tt></a> mode.</li>
<li><tt class="docutils literal"><span class="pre">sql_queries</span></tt> &#8211; A list of <tt class="docutils literal"><span class="pre">{'sql':</span> <span class="pre">...,</span> <span class="pre">'time':</span> <span class="pre">...}</span></tt> dictionaries,
representing every SQL query that has happened so far during the request
and how long it took. The list is in order by query.</li>
</ul>
</div>
<div class="section" id="s-django-core-context-processors-i18n">
<span id="django-core-context-processors-i18n"></span><h4>django.core.context_processors.i18n<a class="headerlink" href="#django-core-context-processors-i18n" title="Permalink to this headline">¶</a></h4>
<p>If <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> contains this processor, every
<tt class="docutils literal"><span class="pre">RequestContext</span></tt> will contain these two variables:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">LANGUAGES</span></tt> &#8211; The value of the <a class="reference internal" href="../settings.html#std:setting-LANGUAGES"><tt class="xref std std-setting docutils literal"><span class="pre">LANGUAGES</span></tt></a> setting.</li>
<li><tt class="docutils literal"><span class="pre">LANGUAGE_CODE</span></tt> &#8211; <tt class="docutils literal"><span class="pre">request.LANGUAGE_CODE</span></tt>, if it exists. Otherwise,
the value of the <a class="reference internal" href="../settings.html#std:setting-LANGUAGE_CODE"><tt class="xref std std-setting docutils literal"><span class="pre">LANGUAGE_CODE</span></tt></a> setting.</li>
</ul>
<p>See <a class="reference internal" href="../../topics/i18n/index.html"><em>Internationalization and localization</em></a> for more.</p>
</div>
<div class="section" id="s-django-core-context-processors-media">
<span id="django-core-context-processors-media"></span><h4>django.core.context_processors.media<a class="headerlink" href="#django-core-context-processors-media" title="Permalink to this headline">¶</a></h4>
<p>If <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> contains this processor, every
<tt class="docutils literal"><span class="pre">RequestContext</span></tt> will contain a variable <tt class="docutils literal"><span class="pre">MEDIA_URL</span></tt>, providing the
value of the <a class="reference internal" href="../settings.html#std:setting-MEDIA_URL"><tt class="xref std std-setting docutils literal"><span class="pre">MEDIA_URL</span></tt></a> setting.</p>
</div>
<div class="section" id="s-django-core-context-processors-static">
<span id="django-core-context-processors-static"></span><h4>django.core.context_processors.static<a class="headerlink" href="#django-core-context-processors-static" title="Permalink to this headline">¶</a></h4>
<dl class="function">
<dt id="django.core.context_processors.static">
<tt class="descname">static</tt>()<a class="headerlink" href="#django.core.context_processors.static" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>If <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> contains this processor, every
<tt class="docutils literal"><span class="pre">RequestContext</span></tt> will contain a variable <tt class="docutils literal"><span class="pre">STATIC_URL</span></tt>, providing the
value of the <a class="reference internal" href="../settings.html#std:setting-STATIC_URL"><tt class="xref std std-setting docutils literal"><span class="pre">STATIC_URL</span></tt></a> setting.</p>
</div>
<div class="section" id="s-django-core-context-processors-csrf">
<span id="django-core-context-processors-csrf"></span><h4>django.core.context_processors.csrf<a class="headerlink" href="#django-core-context-processors-csrf" title="Permalink to this headline">¶</a></h4>
<p>This processor adds a token that is needed by the <a class="reference internal" href="builtins.html#std:templatetag-csrf_token"><tt class="xref std std-ttag docutils literal"><span class="pre">csrf_token</span></tt></a> template
tag for protection against <a class="reference internal" href="../contrib/csrf.html"><em>Cross Site Request Forgeries</em></a>.</p>
</div>
<div class="section" id="s-django-core-context-processors-request">
<span id="django-core-context-processors-request"></span><h4>django.core.context_processors.request<a class="headerlink" href="#django-core-context-processors-request" title="Permalink to this headline">¶</a></h4>
<p>If <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> contains this processor, every
<tt class="docutils literal"><span class="pre">RequestContext</span></tt> will contain a variable <tt class="docutils literal"><span class="pre">request</span></tt>, which is the current
<a class="reference internal" href="../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>. Note that this processor is not enabled by default;
you&#8217;ll have to activate it.</p>
</div>
<div class="section" id="s-django-contrib-messages-context-processors-messages">
<span id="django-contrib-messages-context-processors-messages"></span><h4>django.contrib.messages.context_processors.messages<a class="headerlink" href="#django-contrib-messages-context-processors-messages" title="Permalink to this headline">¶</a></h4>
<p>If <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> contains this processor, every
<tt class="docutils literal"><span class="pre">RequestContext</span></tt> will contain a single additional variable:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">messages</span></tt> &#8211; A list of messages (as strings) that have been set
via the <a class="reference internal" href="../contrib/messages.html"><em>messages framework</em></a>.</li>
</ul>
</div>
<div class="section" id="s-writing-your-own-context-processors">
<span id="writing-your-own-context-processors"></span><h4>Writing your own context processors<a class="headerlink" href="#writing-your-own-context-processors" title="Permalink to this headline">¶</a></h4>
<p>A context processor has a very simple interface: It&#8217;s just a Python function
that takes one argument, an <a class="reference internal" href="../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> object, and
returns a dictionary that gets added to the template context. Each context
processor <em>must</em> return a dictionary.</p>
<p>Custom context processors can live anywhere in your code base. All Django cares
about is that your custom context processors are pointed-to by your
<a class="reference internal" href="../settings.html#std:setting-TEMPLATE_CONTEXT_PROCESSORS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_CONTEXT_PROCESSORS</span></tt></a> setting.</p>
</div>
</div>
<div class="section" id="s-loading-templates">
<span id="loading-templates"></span><h3>Loading templates<a class="headerlink" href="#loading-templates" title="Permalink to this headline">¶</a></h3>
<p>Generally, you&#8217;ll store templates in files on your filesystem rather than using
the low-level <tt class="docutils literal"><span class="pre">Template</span></tt> API yourself. Save templates in a directory
specified as a <strong>template directory</strong>.</p>
<p>Django searches for template directories in a number of places, depending on
your template-loader settings (see &#8220;Loader types&#8221; below), but the most basic
way of specifying template directories is by using the <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_DIRS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_DIRS</span></tt></a>
setting.</p>
<div class="section" id="s-the-template-dirs-setting">
<span id="the-template-dirs-setting"></span><h4>The TEMPLATE_DIRS setting<a class="headerlink" href="#the-template-dirs-setting" title="Permalink to this headline">¶</a></h4>
<p>Tell Django what your template directories are by using the
<a class="reference internal" href="../settings.html#std:setting-TEMPLATE_DIRS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_DIRS</span></tt></a> setting in your settings file. This should be set to a
list or tuple of strings that contain full paths to your template
directory(ies). Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">TEMPLATE_DIRS</span> <span class="o">=</span> <span class="p">(</span>
    <span class="s">&quot;/home/html/templates/lawrence.com&quot;</span><span class="p">,</span>
    <span class="s">&quot;/home/html/templates/default&quot;</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
<p>Your templates can go anywhere you want, as long as the directories and
templates are readable by the Web server. They can have any extension you want,
such as <tt class="docutils literal"><span class="pre">.html</span></tt> or <tt class="docutils literal"><span class="pre">.txt</span></tt>, or they can have no extension at all.</p>
<p>Note that these paths should use Unix-style forward slashes, even on Windows.</p>
</div>
<div class="section" id="s-module-django.template.loader">
<span id="s-the-python-api"></span><span id="s-ref-templates-api-the-python-api"></span><span id="module-django.template.loader"></span><span id="the-python-api"></span><span id="ref-templates-api-the-python-api"></span><h4>The Python API<a class="headerlink" href="#module-django.template.loader" title="Permalink to this headline">¶</a></h4>
<p><tt class="docutils literal"><span class="pre">django.template.loader</span></tt> has two functions to load templates from files:</p>
<dl class="function">
<dt id="django.template.loader.get_template">
<tt class="descname">get_template</tt>(<em>template_name</em>)<a class="reference internal" href="../../_modules/django/template/loader.html#get_template"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.template.loader.get_template" title="Permalink to this definition">¶</a></dt>
<dd><p><tt class="docutils literal"><span class="pre">get_template</span></tt> returns the compiled template (a <tt class="docutils literal"><span class="pre">Template</span></tt> object) for
the template with the given name. If the template doesn&#8217;t exist, it raises
<tt class="docutils literal"><span class="pre">django.template.TemplateDoesNotExist</span></tt>.</p>
</dd></dl>

<dl class="function">
<dt id="django.template.loader.select_template">
<tt class="descname">select_template</tt>(<em>template_name_list</em>)<a class="reference internal" href="../../_modules/django/template/loader.html#select_template"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.template.loader.select_template" title="Permalink to this definition">¶</a></dt>
<dd><p><tt class="docutils literal"><span class="pre">select_template</span></tt> is just like <tt class="docutils literal"><span class="pre">get_template</span></tt>, except it takes a list
of template names. Of the list, it returns the first template that exists.</p>
</dd></dl>

<p>For example, if you call <tt class="docutils literal"><span class="pre">get_template('story_detail.html')</span></tt> and have the
above <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_DIRS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_DIRS</span></tt></a> setting, here are the files Django will look for,
in order:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">/home/html/templates/lawrence.com/story_detail.html</span></tt></li>
<li><tt class="docutils literal"><span class="pre">/home/html/templates/default/story_detail.html</span></tt></li>
</ul>
<p>If you call <tt class="docutils literal"><span class="pre">select_template(['story_253_detail.html',</span> <span class="pre">'story_detail.html'])</span></tt>,
here&#8217;s what Django will look for:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">/home/html/templates/lawrence.com/story_253_detail.html</span></tt></li>
<li><tt class="docutils literal"><span class="pre">/home/html/templates/default/story_253_detail.html</span></tt></li>
<li><tt class="docutils literal"><span class="pre">/home/html/templates/lawrence.com/story_detail.html</span></tt></li>
<li><tt class="docutils literal"><span class="pre">/home/html/templates/default/story_detail.html</span></tt></li>
</ul>
<p>When Django finds a template that exists, it stops looking.</p>
<div class="admonition-tip admonition">
<p class="first admonition-title">Tip</p>
<p class="last">You can use <tt class="docutils literal"><span class="pre">select_template()</span></tt> for super-flexible &#8220;templatability.&#8221; For
example, if you&#8217;ve written a news story and want some stories to have
custom templates, use something like
<tt class="docutils literal"><span class="pre">select_template(['story_%s_detail.html'</span> <span class="pre">%</span> <span class="pre">story.id,</span> <span class="pre">'story_detail.html'])</span></tt>.
That&#8217;ll allow you to use a custom template for an individual story, with a
fallback template for stories that don&#8217;t have custom templates.</p>
</div>
</div>
<div class="section" id="s-using-subdirectories">
<span id="using-subdirectories"></span><h4>Using subdirectories<a class="headerlink" href="#using-subdirectories" title="Permalink to this headline">¶</a></h4>
<p>It&#8217;s possible &#8211; and preferable &#8211; to organize templates in subdirectories of
the template directory. The convention is to make a subdirectory for each
Django app, with subdirectories within those subdirectories as needed.</p>
<p>Do this for your own sanity. Storing all templates in the root level of a
single directory gets messy.</p>
<p>To load a template that&#8217;s within a subdirectory, just use a slash, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">get_template</span><span class="p">(</span><span class="s">&#39;news/story_detail.html&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Using the same <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_DIRS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_DIRS</span></tt></a> setting from above, this example
<tt class="docutils literal"><span class="pre">get_template()</span></tt> call will attempt to load the following templates:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">/home/html/templates/lawrence.com/news/story_detail.html</span></tt></li>
<li><tt class="docutils literal"><span class="pre">/home/html/templates/default/news/story_detail.html</span></tt></li>
</ul>
</div>
<div class="section" id="s-loader-types">
<span id="s-template-loaders"></span><span id="loader-types"></span><span id="template-loaders"></span><h4>Loader types<a class="headerlink" href="#loader-types" title="Permalink to this headline">¶</a></h4>
<p>By default, Django uses a filesystem-based template loader, but Django comes
with a few other template loaders, which know how to load templates from other
sources.</p>
<p>Some of these other loaders are disabled by default, but you can activate them
by editing your <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_LOADERS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_LOADERS</span></tt></a> setting. <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_LOADERS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_LOADERS</span></tt></a>
should be a tuple of strings, where each string represents a template loader
class. Here are the template loaders that come with Django:</p>
<p><tt class="docutils literal"><span class="pre">django.template.loaders.filesystem.Loader</span></tt></p>
<dl class="class">
<dt id="django.template.loaders.filesystem.Loader">
<em class="property">class </em><tt class="descclassname">filesystem.</tt><tt class="descname">Loader</tt><a class="headerlink" href="#django.template.loaders.filesystem.Loader" title="Permalink to this definition">¶</a></dt>
<dd><p>Loads templates from the filesystem, according to <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_DIRS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_DIRS</span></tt></a>.
This loader is enabled by default.</p>
</dd></dl>

<p><tt class="docutils literal"><span class="pre">django.template.loaders.app_directories.Loader</span></tt></p>
<dl class="class">
<dt id="django.template.loaders.app_directories.Loader">
<em class="property">class </em><tt class="descclassname">app_directories.</tt><tt class="descname">Loader</tt><a class="headerlink" href="#django.template.loaders.app_directories.Loader" title="Permalink to this definition">¶</a></dt>
<dd><p>Loads templates from Django apps on the filesystem. For each app in
<a class="reference internal" href="../settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>, the loader looks for a <tt class="docutils literal"><span class="pre">templates</span></tt>
subdirectory. If the directory exists, Django looks for templates in there.</p>
<p>This means you can store templates with your individual apps. This also
makes it easy to distribute Django apps with default templates.</p>
<p>For example, for this setting:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">INSTALLED_APPS</span> <span class="o">=</span> <span class="p">(</span><span class="s">&#39;myproject.polls&#39;</span><span class="p">,</span> <span class="s">&#39;myproject.music&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>...then <tt class="docutils literal"><span class="pre">get_template('foo.html')</span></tt> will look for <tt class="docutils literal"><span class="pre">foo.html</span></tt> in these
directories, in this order:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">/path/to/myproject/polls/templates/</span></tt></li>
<li><tt class="docutils literal"><span class="pre">/path/to/myproject/music/templates/</span></tt></li>
</ul>
<p>... and will use the one it finds first.</p>
<p>The order of <a class="reference internal" href="../settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> is significant! For example, if you
want to customize the Django admin, you might choose to override the
standard <tt class="docutils literal"><span class="pre">admin/base_site.html</span></tt> template, from <tt class="docutils literal"><span class="pre">django.contrib.admin</span></tt>,
with your own <tt class="docutils literal"><span class="pre">admin/base_site.html</span></tt> in <tt class="docutils literal"><span class="pre">myproject.polls</span></tt>. You must
then make sure that your <tt class="docutils literal"><span class="pre">myproject.polls</span></tt> comes <em>before</em>
<tt class="docutils literal"><span class="pre">django.contrib.admin</span></tt> in <a class="reference internal" href="../settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>, otherwise
<tt class="docutils literal"><span class="pre">django.contrib.admin</span></tt>’s will be loaded first and yours will be ignored.</p>
<p>Note that the loader performs an optimization when it is first imported:
it caches a list of which <a class="reference internal" href="../settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> packages have a
<tt class="docutils literal"><span class="pre">templates</span></tt> subdirectory.</p>
<p>This loader is enabled by default.</p>
</dd></dl>

<p><tt class="docutils literal"><span class="pre">django.template.loaders.eggs.Loader</span></tt></p>
<dl class="class">
<dt id="django.template.loaders.eggs.Loader">
<em class="property">class </em><tt class="descclassname">eggs.</tt><tt class="descname">Loader</tt><a class="headerlink" href="#django.template.loaders.eggs.Loader" title="Permalink to this definition">¶</a></dt>
<dd><p>Just like <tt class="docutils literal"><span class="pre">app_directories</span></tt> above, but it loads templates from Python
eggs rather than from the filesystem.</p>
<p>This loader is disabled by default.</p>
</dd></dl>

<p><tt class="docutils literal"><span class="pre">django.template.loaders.cached.Loader</span></tt></p>
<dl class="class">
<dt id="django.template.loaders.cached.Loader">
<em class="property">class </em><tt class="descclassname">cached.</tt><tt class="descname">Loader</tt><a class="headerlink" href="#django.template.loaders.cached.Loader" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, the templating system will read and compile your templates every
time they need to be rendered. While the Django templating system is quite
fast, the overhead from reading and compiling templates can add up.</p>
<p>The cached template loader is a class-based loader that you configure with
a list of other loaders that it should wrap. The wrapped loaders are used to
locate unknown templates when they are first encountered. The cached loader
then stores the compiled <tt class="docutils literal"><span class="pre">Template</span></tt> in memory. The cached <tt class="docutils literal"><span class="pre">Template</span></tt>
instance is returned for subsequent requests to load the same template.</p>
<p>For example, to enable template caching with the <tt class="docutils literal"><span class="pre">filesystem</span></tt> and
<tt class="docutils literal"><span class="pre">app_directories</span></tt> template loaders you might use the following settings:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">TEMPLATE_LOADERS</span> <span class="o">=</span> <span class="p">(</span>
    <span class="p">(</span><span class="s">&#39;django.template.loaders.cached.Loader&#39;</span><span class="p">,</span> <span class="p">(</span>
        <span class="s">&#39;django.template.loaders.filesystem.Loader&#39;</span><span class="p">,</span>
        <span class="s">&#39;django.template.loaders.app_directories.Loader&#39;</span><span class="p">,</span>
    <span class="p">)),</span>
<span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">All of the built-in Django template tags are safe to use with the
cached loader, but if you&#8217;re using custom template tags that come from
third party packages, or that you wrote yourself, you should ensure
that the <tt class="docutils literal"><span class="pre">Node</span></tt> implementation for each tag is thread-safe. For more
information, see <a class="reference internal" href="../../howto/custom-template-tags.html#template-tag-thread-safety"><em>template tag thread safety
considerations</em></a>.</p>
</div>
<p>This loader is disabled by default.</p>
</dd></dl>

<p>Django uses the template loaders in order according to the
<a class="reference internal" href="../settings.html#std:setting-TEMPLATE_LOADERS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_LOADERS</span></tt></a> setting. It uses each loader until a loader finds a
match.</p>
</div>
</div>
</div>
<div class="section" id="s-the-render-to-string-shortcut">
<span id="the-render-to-string-shortcut"></span><h2>The <tt class="docutils literal"><span class="pre">render_to_string</span></tt> shortcut<a class="headerlink" href="#the-render-to-string-shortcut" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="django.template.loaders.django.template.loader.render_to_string">
<tt class="descclassname">django.template.loader.</tt><tt class="descname">render_to_string</tt>(<em>template_name</em>, <em>dictionary=None</em>, <em>context_instance=None</em>)<a class="headerlink" href="#django.template.loaders.django.template.loader.render_to_string" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>To cut down on the repetitive nature of loading and rendering
templates, Django provides a shortcut function which largely
automates the process: <tt class="docutils literal"><span class="pre">render_to_string()</span></tt> in
<a class="reference internal" href="#module-django.template.loader" title="django.template.loader"><tt class="xref py py-mod docutils literal"><span class="pre">django.template.loader</span></tt></a>, which loads a template, renders it and
returns the resulting string:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.template.loader</span> <span class="kn">import</span> <span class="n">render_to_string</span>
<span class="n">rendered</span> <span class="o">=</span> <span class="n">render_to_string</span><span class="p">(</span><span class="s">&#39;my_template.html&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;foo&#39;</span><span class="p">:</span> <span class="s">&#39;bar&#39;</span><span class="p">})</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">render_to_string</span></tt> shortcut takes one required argument &#8211;
<tt class="docutils literal"><span class="pre">template_name</span></tt>, which should be the name of the template to load
and render (or a list of template names, in which case Django will use
the first template in the list that exists) &#8211; and two optional arguments:</p>
<dl class="docutils">
<dt>dictionary</dt>
<dd>A dictionary to be used as variables and values for the
template&#8217;s context. This can also be passed as the second
positional argument.</dd>
<dt>context_instance</dt>
<dd>An instance of <a class="reference internal" href="#django.template.Context" title="django.template.Context"><tt class="xref py py-class docutils literal"><span class="pre">Context</span></tt></a> or a subclass (e.g., an
instance of <a class="reference internal" href="#django.template.RequestContext" title="django.template.RequestContext"><tt class="xref py py-class docutils literal"><span class="pre">RequestContext</span></tt></a>) to use as the
template&#8217;s context. This can also be passed as the third positional argument.</dd>
</dl>
<p>See also the <a class="reference internal" href="../../topics/http/shortcuts.html#django.shortcuts.render_to_response" title="django.shortcuts.render_to_response"><tt class="xref py py-func docutils literal"><span class="pre">render_to_response()</span></tt></a> shortcut, which
calls <tt class="docutils literal"><span class="pre">render_to_string</span></tt> and feeds the result into an <a class="reference internal" href="../request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><tt class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></tt></a>
suitable for returning directly from a view.</p>
</div>
<div class="section" id="s-configuring-the-template-system-in-standalone-mode">
<span id="configuring-the-template-system-in-standalone-mode"></span><h2>Configuring the template system in standalone mode<a class="headerlink" href="#configuring-the-template-system-in-standalone-mode" title="Permalink to this headline">¶</a></h2>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This section is only of interest to people trying to use the template
system as an output component in another application. If you&#8217;re using the
template system as part of a Django application, nothing here applies to
you.</p>
</div>
<p>Normally, Django will load all the configuration information it needs from its
own default configuration file, combined with the settings in the module given
in the <span class="target" id="index-0"></span><a class="reference internal" href="../../topics/settings.html#envvar-DJANGO_SETTINGS_MODULE"><tt class="xref std std-envvar docutils literal"><span class="pre">DJANGO_SETTINGS_MODULE</span></tt></a> environment variable. But if you&#8217;re
using the template system independently of the rest of Django, the environment
variable approach isn&#8217;t very convenient, because you probably want to configure
the template system in line with the rest of your application rather than
dealing with settings files and pointing to them via environment variables.</p>
<p>To solve this problem, you need to use the manual configuration option described
in <a class="reference internal" href="../../topics/settings.html#settings-without-django-settings-module"><em>Using settings without setting DJANGO_SETTINGS_MODULE</em></a>. Simply import the appropriate
pieces of the templating system and then, <em>before</em> you call any of the
templating functions, call <a class="reference internal" href="../../topics/settings.html#django.conf.settings.configure" title="django.conf.settings.configure"><tt class="xref py py-func docutils literal"><span class="pre">django.conf.settings.configure()</span></tt></a> with any
settings you wish to specify. You might want to consider setting at least
<a class="reference internal" href="../settings.html#std:setting-TEMPLATE_DIRS"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_DIRS</span></tt></a> (if you&#8217;re going to use template loaders),
<a class="reference internal" href="../settings.html#std:setting-DEFAULT_CHARSET"><tt class="xref std std-setting docutils literal"><span class="pre">DEFAULT_CHARSET</span></tt></a> (although the default of <tt class="docutils literal"><span class="pre">utf-8</span></tt> is probably fine)
and <a class="reference internal" href="../settings.html#std:setting-TEMPLATE_DEBUG"><tt class="xref std std-setting docutils literal"><span class="pre">TEMPLATE_DEBUG</span></tt></a>. If you plan to use the <a class="reference internal" href="builtins.html#std:templatetag-url"><tt class="xref std std-ttag docutils literal"><span class="pre">url</span></tt></a> template tag,
you will also need to set the <a class="reference internal" href="../settings.html#std:setting-ROOT_URLCONF"><tt class="xref std std-setting docutils literal"><span class="pre">ROOT_URLCONF</span></tt></a> setting. All available
settings are described in the <a class="reference internal" href="../settings.html"><em>settings documentation</em></a>,
and any setting starting with <tt class="docutils literal"><span class="pre">TEMPLATE_</span></tt> is of obvious interest.</p>
</div>
<div class="section" id="s-using-an-alternative-template-language">
<span id="s-topic-template-alternate-language"></span><span id="using-an-alternative-template-language"></span><span id="topic-template-alternate-language"></span><h2>Using an alternative template language<a class="headerlink" href="#using-an-alternative-template-language" title="Permalink to this headline">¶</a></h2>
<p>The Django <tt class="docutils literal"><span class="pre">Template</span></tt> and <tt class="docutils literal"><span class="pre">Loader</span></tt> classes implement a simple API for
loading and rendering templates. By providing some simple wrapper classes that
implement this API we can use third party template systems like <a class="reference external" href="http://jinja.pocoo.org/docs/">Jinja2</a> or <a class="reference external" href="http://www.cheetahtemplate.org/">Cheetah</a>. This
allows us to use third-party template libraries without giving up useful Django
features like the Django <tt class="docutils literal"><span class="pre">Context</span></tt> object and handy shortcuts like
<a class="reference internal" href="../../topics/http/shortcuts.html#django.shortcuts.render_to_response" title="django.shortcuts.render_to_response"><tt class="xref py py-func docutils literal"><span class="pre">render_to_response()</span></tt></a>.</p>
<p>The core component of the Django templating system is the <tt class="docutils literal"><span class="pre">Template</span></tt> class.
This class has a very simple interface: it has a constructor that takes a single
positional argument specifying the template string, and a <tt class="docutils literal"><span class="pre">render()</span></tt> method
that takes a <a class="reference internal" href="#django.template.Context" title="django.template.Context"><tt class="xref py py-class docutils literal"><span class="pre">Context</span></tt></a> object and returns a string
containing the rendered response.</p>
<p>Suppose we&#8217;re using a template language that defines a <tt class="docutils literal"><span class="pre">Template</span></tt> object with
a <tt class="docutils literal"><span class="pre">render()</span></tt> method that takes a dictionary rather than a <tt class="docutils literal"><span class="pre">Context</span></tt> object.
We can write a simple wrapper that implements the Django <tt class="docutils literal"><span class="pre">Template</span></tt> interface:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">some_template_language</span>
<span class="k">class</span> <span class="nc">Template</span><span class="p">(</span><span class="n">some_template_language</span><span class="o">.</span><span class="n">Template</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">render</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
        <span class="c"># flatten the Django Context into a single dictionary.</span>
        <span class="n">context_dict</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">context</span><span class="o">.</span><span class="n">dicts</span><span class="p">:</span>
            <span class="n">context_dict</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">Template</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">context_dict</span><span class="p">)</span>
</pre></div>
</div>
<p>That&#8217;s all that&#8217;s required to make our fictional <tt class="docutils literal"><span class="pre">Template</span></tt> class compatible
with the Django loading and rendering system!</p>
<p>The next step is to write a <tt class="docutils literal"><span class="pre">Loader</span></tt> class that returns instances of our custom
template class instead of the default <a class="reference internal" href="#django.template.Template" title="django.template.Template"><tt class="xref py py-class docutils literal"><span class="pre">Template</span></tt></a>. Custom <tt class="docutils literal"><span class="pre">Loader</span></tt>
classes should inherit from <tt class="docutils literal"><span class="pre">django.template.loader.BaseLoader</span></tt> and override
the <tt class="docutils literal"><span class="pre">load_template_source()</span></tt> method, which takes a <tt class="docutils literal"><span class="pre">template_name</span></tt> argument,
loads the template from disk (or elsewhere), and returns a tuple:
<tt class="docutils literal"><span class="pre">(template_string,</span> <span class="pre">template_origin)</span></tt>.</p>
<p>The <tt class="docutils literal"><span class="pre">load_template()</span></tt> method of the <tt class="docutils literal"><span class="pre">Loader</span></tt> class retrieves the template
string by calling <tt class="docutils literal"><span class="pre">load_template_source()</span></tt>, instantiates a <tt class="docutils literal"><span class="pre">Template</span></tt> from
the template source, and returns a tuple: <tt class="docutils literal"><span class="pre">(template,</span> <span class="pre">template_origin)</span></tt>. Since
this is the method that actually instantiates the <tt class="docutils literal"><span class="pre">Template</span></tt>, we&#8217;ll need to
override it to use our custom template class instead. We can inherit from the
builtin <a class="reference internal" href="#django.template.loaders.app_directories.Loader" title="django.template.loaders.app_directories.Loader"><tt class="xref py py-class docutils literal"><span class="pre">django.template.loaders.app_directories.Loader</span></tt></a> to take advantage
of the <tt class="docutils literal"><span class="pre">load_template_source()</span></tt> method implemented there:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.template.loaders</span> <span class="kn">import</span> <span class="n">app_directories</span>
<span class="k">class</span> <span class="nc">Loader</span><span class="p">(</span><span class="n">app_directories</span><span class="o">.</span><span class="n">Loader</span><span class="p">):</span>
    <span class="n">is_usable</span> <span class="o">=</span> <span class="bp">True</span>

    <span class="k">def</span> <span class="nf">load_template</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">template_name</span><span class="p">,</span> <span class="n">template_dirs</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="n">source</span><span class="p">,</span> <span class="n">origin</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">load_template_source</span><span class="p">(</span><span class="n">template_name</span><span class="p">,</span> <span class="n">template_dirs</span><span class="p">)</span>
        <span class="n">template</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="n">source</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">template</span><span class="p">,</span> <span class="n">origin</span>
</pre></div>
</div>
<p>Finally, we need to modify our project settings, telling Django to use our custom
loader. Now we can write all of our templates in our alternative template
language while continuing to use the rest of the Django templating system.</p>
</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="#">The Django template language: For Python programmers</a><ul>
<li><a class="reference internal" href="#basics">Basics</a></li>
<li><a class="reference internal" href="#using-the-template-system">Using the template system</a><ul>
<li><a class="reference internal" href="#compiling-a-string">Compiling a string</a></li>
<li><a class="reference internal" href="#rendering-a-context">Rendering a context</a><ul>
<li><a class="reference internal" href="#variables-and-lookups">Variables and lookups</a></li>
<li><a class="reference internal" href="#how-invalid-variables-are-handled">How invalid variables are handled</a></li>
<li><a class="reference internal" href="#builtin-variables">Builtin variables</a></li>
</ul>
</li>
<li><a class="reference internal" href="#playing-with-context-objects">Playing with Context objects</a></li>
<li><a class="reference internal" href="#subclassing-context-requestcontext">Subclassing Context: RequestContext</a><ul>
<li><a class="reference internal" href="#django-contrib-auth-context-processors-auth">django.contrib.auth.context_processors.auth</a></li>
<li><a class="reference internal" href="#django-core-context-processors-debug">django.core.context_processors.debug</a></li>
<li><a class="reference internal" href="#django-core-context-processors-i18n">django.core.context_processors.i18n</a></li>
<li><a class="reference internal" href="#django-core-context-processors-media">django.core.context_processors.media</a></li>
<li><a class="reference internal" href="#django-core-context-processors-static">django.core.context_processors.static</a></li>
<li><a class="reference internal" href="#django-core-context-processors-csrf">django.core.context_processors.csrf</a></li>
<li><a class="reference internal" href="#django-core-context-processors-request">django.core.context_processors.request</a></li>
<li><a class="reference internal" href="#django-contrib-messages-context-processors-messages">django.contrib.messages.context_processors.messages</a></li>
<li><a class="reference internal" href="#writing-your-own-context-processors">Writing your own context processors</a></li>
</ul>
</li>
<li><a class="reference internal" href="#loading-templates">Loading templates</a><ul>
<li><a class="reference internal" href="#the-template-dirs-setting">The TEMPLATE_DIRS setting</a></li>
<li><a class="reference internal" href="#module-django.template.loader">The Python API</a></li>
<li><a class="reference internal" href="#using-subdirectories">Using subdirectories</a></li>
<li><a class="reference internal" href="#loader-types">Loader types</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#the-render-to-string-shortcut">The <tt class="docutils literal"><span class="pre">render_to_string</span></tt> shortcut</a></li>
<li><a class="reference internal" href="#configuring-the-template-system-in-standalone-mode">Configuring the template system in standalone mode</a></li>
<li><a class="reference internal" href="#using-an-alternative-template-language">Using an alternative template language</a></li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="builtins.html">Built-in template tags and filters</a></li>
    
    
      <li>Next: <a href="../unicode.html">Unicode data</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django 1.6.7 documentation</a>
        
          <ul><li><a href="../index.html">API Reference</a>
        
          <ul><li><a href="index.html">Templates</a>
        
        <ul><li>The Django template language: For Python programmers</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>  

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../_sources/ref/templates/api.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">Sep 26, 2014</p>
          </div> 
        
      
    </div>
    
    <div id="ft">
      <div class="nav">
    &laquo; <a href="builtins.html" title="Built-in template tags and filters">previous</a> 
     |
    <a href="../index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="../unicode.html" title="Unicode data">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>