api.txt 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. .. _ref-templates-api:
  2. ====================================================
  3. The Django template language: For Python programmers
  4. ====================================================
  5. This document explains the Django template system from a technical
  6. perspective -- how it works and how to extend it. If you're just looking for
  7. reference on the language syntax, see :ref:`topics-templates`.
  8. If you're looking to use the Django template system as part of another
  9. application -- i.e., without the rest of the framework -- make sure to read
  10. the `configuration`_ section later in this document.
  11. .. _configuration: `configuring the template system in standalone mode`_
  12. Basics
  13. ======
  14. A **template** is a text document, or a normal Python string, that is marked-up
  15. using the Django template language. A template can contain **block tags** or
  16. **variables**.
  17. A **block tag** is a symbol within a template that does something.
  18. This definition is deliberately vague. For example, a block tag can output
  19. content, serve as a control structure (an "if" statement or "for" loop), grab
  20. content from a database or enable access to other template tags.
  21. Block tags are surrounded by ``"{%"`` and ``"%}"``.
  22. Example template with block tags:
  23. .. code-block:: html+django
  24. {% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}
  25. A **variable** is a symbol within a template that outputs a value.
  26. Variable tags are surrounded by ``"{{"`` and ``"}}"``.
  27. Example template with variables:
  28. .. code-block:: html+django
  29. My first name is {{ first_name }}. My last name is {{ last_name }}.
  30. A **context** is a "variable name" -> "variable value" mapping that is passed
  31. to a template.
  32. A template **renders** a context by replacing the variable "holes" with values
  33. from the context and executing all block tags.
  34. Using the template system
  35. =========================
  36. Using the template system in Python is a two-step process:
  37. * First, you compile the raw template code into a ``Template`` object.
  38. * Then, you call the ``render()`` method of the ``Template`` object with a
  39. given context.
  40. Compiling a string
  41. ------------------
  42. The easiest way to create a ``Template`` object is by instantiating it
  43. directly. The class lives at ``django.template.Template``. The constructor
  44. takes one argument -- the raw template code::
  45. >>> from django.template import Template
  46. >>> t = Template("My name is {{ my_name }}.")
  47. >>> print t
  48. <django.template.Template instance>
  49. .. admonition:: Behind the scenes
  50. The system only parses your raw template code once -- when you create the
  51. ``Template`` object. From then on, it's stored internally as a "node"
  52. structure for performance.
  53. Even the parsing itself is quite fast. Most of the parsing happens via a
  54. single call to a single, short, regular expression.
  55. Rendering a context
  56. -------------------
  57. Once you have a compiled ``Template`` object, you can render a context -- or
  58. multiple contexts -- with it. The ``Context`` class lives at
  59. ``django.template.Context``, and the constructor takes two (optional)
  60. arguments:
  61. * A dictionary mapping variable names to variable values.
  62. * The name of the current application. This application name is used
  63. to help :ref:`resolve namespaced URLs<topics-http-reversing-url-namespaces>`.
  64. If you're not using namespaced URLs, you can ignore this argument.
  65. Call the ``Template`` object's ``render()`` method with the context to "fill" the
  66. template::
  67. >>> from django.template import Context, Template
  68. >>> t = Template("My name is {{ my_name }}.")
  69. >>> c = Context({"my_name": "Adrian"})
  70. >>> t.render(c)
  71. "My name is Adrian."
  72. >>> c = Context({"my_name": "Dolores"})
  73. >>> t.render(c)
  74. "My name is Dolores."
  75. Variable names must consist of any letter (A-Z), any digit (0-9), an underscore
  76. or a dot.
  77. Dots have a special meaning in template rendering. A dot in a variable name
  78. signifies **lookup**. Specifically, when the template system encounters a dot
  79. in a variable name, it tries the following lookups, in this order:
  80. * Dictionary lookup. Example: ``foo["bar"]``
  81. * Attribute lookup. Example: ``foo.bar``
  82. * Method call. Example: ``foo.bar()``
  83. * List-index lookup. Example: ``foo[bar]``
  84. The template system uses the first lookup type that works. It's short-circuit
  85. logic.
  86. Here are a few examples::
  87. >>> from django.template import Context, Template
  88. >>> t = Template("My name is {{ person.first_name }}.")
  89. >>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
  90. >>> t.render(Context(d))
  91. "My name is Joe."
  92. >>> class PersonClass: pass
  93. >>> p = PersonClass()
  94. >>> p.first_name = "Ron"
  95. >>> p.last_name = "Nasty"
  96. >>> t.render(Context({"person": p}))
  97. "My name is Ron."
  98. >>> class PersonClass2:
  99. ... def first_name(self):
  100. ... return "Samantha"
  101. >>> p = PersonClass2()
  102. >>> t.render(Context({"person": p}))
  103. "My name is Samantha."
  104. >>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
  105. >>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
  106. >>> t.render(c)
  107. "The first stooge in the list is Larry."
  108. Method lookups are slightly more complex than the other lookup types. Here are
  109. some things to keep in mind:
  110. * If, during the method lookup, a method raises an exception, the exception
  111. will be propagated, unless the exception has an attribute
  112. ``silent_variable_failure`` whose value is ``True``. If the exception
  113. *does* have a ``silent_variable_failure`` attribute, the variable will
  114. render as an empty string. Example::
  115. >>> t = Template("My name is {{ person.first_name }}.")
  116. >>> class PersonClass3:
  117. ... def first_name(self):
  118. ... raise AssertionError, "foo"
  119. >>> p = PersonClass3()
  120. >>> t.render(Context({"person": p}))
  121. Traceback (most recent call last):
  122. ...
  123. AssertionError: foo
  124. >>> class SilentAssertionError(Exception):
  125. ... silent_variable_failure = True
  126. >>> class PersonClass4:
  127. ... def first_name(self):
  128. ... raise SilentAssertionError
  129. >>> p = PersonClass4()
  130. >>> t.render(Context({"person": p}))
  131. "My name is ."
  132. Note that ``django.core.exceptions.ObjectDoesNotExist``, which is the
  133. base class for all Django database API ``DoesNotExist`` exceptions, has
  134. ``silent_variable_failure = True``. So if you're using Django templates
  135. with Django model objects, any ``DoesNotExist`` exception will fail
  136. silently.
  137. * A method call will only work if the method has no required arguments.
  138. Otherwise, the system will move to the next lookup type (list-index
  139. lookup).
  140. * Obviously, some methods have side effects, and it'd be either foolish or
  141. a security hole to allow the template system to access them.
  142. A good example is the ``delete()`` method on each Django model object.
  143. The template system shouldn't be allowed to do something like this::
  144. I will now delete this valuable data. {{ data.delete }}
  145. To prevent this, set a function attribute ``alters_data`` on the method.
  146. The template system won't execute a method if the method has
  147. ``alters_data=True`` set. The dynamically-generated ``delete()`` and
  148. ``save()`` methods on Django model objects get ``alters_data=True``
  149. automatically. Example::
  150. def sensitive_function(self):
  151. self.database_record.delete()
  152. sensitive_function.alters_data = True
  153. .. _invalid-template-variables:
  154. How invalid variables are handled
  155. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  156. Generally, if a variable doesn't exist, the template system inserts the
  157. value of the :setting:`TEMPLATE_STRING_IF_INVALID` setting, which is set to
  158. ``''`` (the empty string) by default.
  159. Filters that are applied to an invalid variable will only be applied if
  160. :setting:`TEMPLATE_STRING_IF_INVALID` is set to ``''`` (the empty string). If
  161. :setting:`TEMPLATE_STRING_IF_INVALID` is set to any other value, variable
  162. filters will be ignored.
  163. This behavior is slightly different for the ``if``, ``for`` and ``regroup``
  164. template tags. If an invalid variable is provided to one of these template
  165. tags, the variable will be interpreted as ``None``. Filters are always
  166. applied to invalid variables within these template tags.
  167. If :setting:`TEMPLATE_STRING_IF_INVALID` contains a ``'%s'``, the format marker will
  168. be replaced with the name of the invalid variable.
  169. .. admonition:: For debug purposes only!
  170. While :setting:`TEMPLATE_STRING_IF_INVALID` can be a useful debugging tool,
  171. it is a bad idea to turn it on as a 'development default'.
  172. Many templates, including those in the Admin site, rely upon the
  173. silence of the template system when a non-existent variable is
  174. encountered. If you assign a value other than ``''`` to
  175. :setting:`TEMPLATE_STRING_IF_INVALID`, you will experience rendering
  176. problems with these templates and sites.
  177. Generally, :setting:`TEMPLATE_STRING_IF_INVALID` should only be enabled
  178. in order to debug a specific template problem, then cleared
  179. once debugging is complete.
  180. Playing with Context objects
  181. ----------------------------
  182. Most of the time, you'll instantiate ``Context`` objects by passing in a
  183. fully-populated dictionary to ``Context()``. But you can add and delete items
  184. from a ``Context`` object once it's been instantiated, too, using standard
  185. dictionary syntax::
  186. >>> c = Context({"foo": "bar"})
  187. >>> c['foo']
  188. 'bar'
  189. >>> del c['foo']
  190. >>> c['foo']
  191. ''
  192. >>> c['newvariable'] = 'hello'
  193. >>> c['newvariable']
  194. 'hello'
  195. A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it.
  196. If you ``pop()`` too much, it'll raise
  197. ``django.template.ContextPopException``::
  198. >>> c = Context()
  199. >>> c['foo'] = 'first level'
  200. >>> c.push()
  201. >>> c['foo'] = 'second level'
  202. >>> c['foo']
  203. 'second level'
  204. >>> c.pop()
  205. >>> c['foo']
  206. 'first level'
  207. >>> c['foo'] = 'overwritten'
  208. >>> c['foo']
  209. 'overwritten'
  210. >>> c.pop()
  211. Traceback (most recent call last):
  212. ...
  213. django.template.ContextPopException
  214. Using a ``Context`` as a stack comes in handy in some custom template tags, as
  215. you'll see below.
  216. .. _subclassing-context-requestcontext:
  217. Subclassing Context: RequestContext
  218. -----------------------------------
  219. Django comes with a special ``Context`` class,
  220. ``django.template.RequestContext``, that acts slightly differently than the
  221. normal ``django.template.Context``. The first difference is that it takes an
  222. :class:`~django.http.HttpRequest` as its first argument. For example::
  223. c = RequestContext(request, {
  224. 'foo': 'bar',
  225. })
  226. The second difference is that it automatically populates the context with a few
  227. variables, according to your :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
  228. The :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting is a tuple of callables --
  229. called **context processors** -- that take a request object as their argument
  230. and return a dictionary of items to be merged into the context. By default,
  231. :setting:`TEMPLATE_CONTEXT_PROCESSORS` is set to::
  232. ("django.core.context_processors.auth",
  233. "django.core.context_processors.debug",
  234. "django.core.context_processors.i18n",
  235. "django.core.context_processors.media")
  236. .. versionadded:: 1.2
  237. In addition to these, ``RequestContext`` always uses
  238. ``'django.core.context_processors.csrf'``. This is a security
  239. related context processor required by the admin and other contrib apps, and,
  240. in case of accidental misconfiguration, it is deliberately hardcoded in and
  241. cannot be turned off by the :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
  242. Each processor is applied in order. That means, if one processor adds a
  243. variable to the context and a second processor adds a variable with the same
  244. name, the second will override the first. The default processors are explained
  245. below.
  246. Also, you can give ``RequestContext`` a list of additional processors, using the
  247. optional, third positional argument, ``processors``. In this example, the
  248. ``RequestContext`` instance gets a ``ip_address`` variable::
  249. def ip_address_processor(request):
  250. return {'ip_address': request.META['REMOTE_ADDR']}
  251. def some_view(request):
  252. # ...
  253. c = RequestContext(request, {
  254. 'foo': 'bar',
  255. }, [ip_address_processor])
  256. return HttpResponse(t.render(c))
  257. .. note::
  258. If you're using Django's ``render_to_response()`` shortcut to populate a
  259. template with the contents of a dictionary, your template will be passed a
  260. ``Context`` instance by default (not a ``RequestContext``). To use a
  261. ``RequestContext`` in your template rendering, pass an optional third
  262. argument to ``render_to_response()``: a ``RequestContext``
  263. instance. Your code might look like this::
  264. def some_view(request):
  265. # ...
  266. return render_to_response('my_template.html',
  267. my_data_dictionary,
  268. context_instance=RequestContext(request))
  269. Here's what each of the default processors does:
  270. django.core.context_processors.auth
  271. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  272. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  273. ``RequestContext`` will contain these three variables:
  274. * ``user`` -- An ``auth.User`` instance representing the currently
  275. logged-in user (or an ``AnonymousUser`` instance, if the client isn't
  276. logged in).
  277. * ``messages`` -- A list of messages (as strings) for the currently
  278. logged-in user. Behind the scenes, this calls
  279. ``request.user.get_and_delete_messages()`` for every request. That method
  280. collects the user's messages and deletes them from the database.
  281. Note that messages are set with ``user.message_set.create``.
  282. * ``perms`` -- An instance of
  283. ``django.core.context_processors.PermWrapper``, representing the
  284. permissions that the currently logged-in user has.
  285. django.core.context_processors.debug
  286. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  287. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  288. ``RequestContext`` will contain these two variables -- but only if your
  289. :setting:`DEBUG` setting is set to ``True`` and the request's IP address
  290. (``request.META['REMOTE_ADDR']``) is in the :setting:`INTERNAL_IPS` setting:
  291. * ``debug`` -- ``True``. You can use this in templates to test whether
  292. you're in :setting:`DEBUG` mode.
  293. * ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries,
  294. representing every SQL query that has happened so far during the request
  295. and how long it took. The list is in order by query.
  296. django.core.context_processors.i18n
  297. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  298. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  299. ``RequestContext`` will contain these two variables:
  300. * ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting.
  301. * ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise,
  302. the value of the :setting:`LANGUAGE_CODE` setting.
  303. See :ref:`topics-i18n` for more.
  304. django.core.context_processors.media
  305. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  306. .. versionadded:: 1.0
  307. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  308. ``RequestContext`` will contain a variable ``MEDIA_URL``, providing the
  309. value of the :setting:`MEDIA_URL` setting.
  310. django.core.context_processors.csrf
  311. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  312. .. versionadded:: 1.2
  313. This processor adds a token that is needed by the ``csrf_token`` template tag
  314. for protection against :ref:`Cross Site Request Forgeries <ref-contrib-csrf>`.
  315. django.core.context_processors.request
  316. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  317. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  318. ``RequestContext`` will contain a variable ``request``, which is the current
  319. :class:`~django.http.HttpRequest`. Note that this processor is not enabled by default;
  320. you'll have to activate it.
  321. Writing your own context processors
  322. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  323. A context processor has a very simple interface: It's just a Python function
  324. that takes one argument, an ``HttpRequest`` object, and returns a dictionary
  325. that gets added to the template context. Each context processor *must* return
  326. a dictionary.
  327. Custom context processors can live anywhere in your code base. All Django cares
  328. about is that your custom context processors are pointed-to by your
  329. :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
  330. Loading templates
  331. -----------------
  332. Generally, you'll store templates in files on your filesystem rather than using
  333. the low-level ``Template`` API yourself. Save templates in a directory
  334. specified as a **template directory**.
  335. Django searches for template directories in a number of places, depending on
  336. your template-loader settings (see "Loader types" below), but the most basic
  337. way of specifying template directories is by using the :setting:`TEMPLATE_DIRS`
  338. setting.
  339. The TEMPLATE_DIRS setting
  340. ~~~~~~~~~~~~~~~~~~~~~~~~~
  341. Tell Django what your template directories are by using the
  342. :setting:`TEMPLATE_DIRS` setting in your settings file. This should be set to a
  343. list or tuple of strings that contain full paths to your template
  344. directory(ies). Example::
  345. TEMPLATE_DIRS = (
  346. "/home/html/templates/lawrence.com",
  347. "/home/html/templates/default",
  348. )
  349. Your templates can go anywhere you want, as long as the directories and
  350. templates are readable by the Web server. They can have any extension you want,
  351. such as ``.html`` or ``.txt``, or they can have no extension at all.
  352. Note that these paths should use Unix-style forward slashes, even on Windows.
  353. .. _ref-templates-api-the-python-api:
  354. The Python API
  355. ~~~~~~~~~~~~~~
  356. Django has two ways to load templates from files:
  357. ``django.template.loader.get_template(template_name)``
  358. ``get_template`` returns the compiled template (a ``Template`` object) for
  359. the template with the given name. If the template doesn't exist, it raises
  360. ``django.template.TemplateDoesNotExist``.
  361. ``django.template.loader.select_template(template_name_list)``
  362. ``select_template`` is just like ``get_template``, except it takes a list
  363. of template names. Of the list, it returns the first template that exists.
  364. For example, if you call ``get_template('story_detail.html')`` and have the
  365. above :setting:`TEMPLATE_DIRS` setting, here are the files Django will look for,
  366. in order:
  367. * ``/home/html/templates/lawrence.com/story_detail.html``
  368. * ``/home/html/templates/default/story_detail.html``
  369. If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,
  370. here's what Django will look for:
  371. * ``/home/html/templates/lawrence.com/story_253_detail.html``
  372. * ``/home/html/templates/default/story_253_detail.html``
  373. * ``/home/html/templates/lawrence.com/story_detail.html``
  374. * ``/home/html/templates/default/story_detail.html``
  375. When Django finds a template that exists, it stops looking.
  376. .. admonition:: Tip
  377. You can use ``select_template()`` for super-flexible "templatability." For
  378. example, if you've written a news story and want some stories to have
  379. custom templates, use something like
  380. ``select_template(['story_%s_detail.html' % story.id, 'story_detail.html'])``.
  381. That'll allow you to use a custom template for an individual story, with a
  382. fallback template for stories that don't have custom templates.
  383. Using subdirectories
  384. ~~~~~~~~~~~~~~~~~~~~
  385. It's possible -- and preferable -- to organize templates in subdirectories of
  386. the template directory. The convention is to make a subdirectory for each
  387. Django app, with subdirectories within those subdirectories as needed.
  388. Do this for your own sanity. Storing all templates in the root level of a
  389. single directory gets messy.
  390. To load a template that's within a subdirectory, just use a slash, like so::
  391. get_template('news/story_detail.html')
  392. Using the same :setting:`TEMPLATE_DIRS` setting from above, this example
  393. ``get_template()`` call will attempt to load the following templates:
  394. * ``/home/html/templates/lawrence.com/news/story_detail.html``
  395. * ``/home/html/templates/default/news/story_detail.html``
  396. .. _template-loaders:
  397. Loader types
  398. ~~~~~~~~~~~~
  399. By default, Django uses a filesystem-based template loader, but Django comes
  400. with a few other template loaders, which know how to load templates from other
  401. sources.
  402. Some of these other loaders are disabled by default, but you can activate them
  403. by editing your :setting:`TEMPLATE_LOADERS` setting. :setting:`TEMPLATE_LOADERS`
  404. should be a tuple of strings, where each string represents a template loader.
  405. Here are the template loaders that come with Django:
  406. ``django.template.loaders.filesystem.load_template_source``
  407. Loads templates from the filesystem, according to :setting:`TEMPLATE_DIRS`.
  408. This loader is enabled by default.
  409. ``django.template.loaders.app_directories.load_template_source``
  410. Loads templates from Django apps on the filesystem. For each app in
  411. :setting:`INSTALLED_APPS`, the loader looks for a ``templates``
  412. subdirectory. If the directory exists, Django looks for templates in there.
  413. This means you can store templates with your individual apps. This also
  414. makes it easy to distribute Django apps with default templates.
  415. For example, for this setting::
  416. INSTALLED_APPS = ('myproject.polls', 'myproject.music')
  417. ...then ``get_template('foo.html')`` will look for templates in these
  418. directories, in this order:
  419. * ``/path/to/myproject/polls/templates/foo.html``
  420. * ``/path/to/myproject/music/templates/foo.html``
  421. Note that the loader performs an optimization when it is first imported: It
  422. caches a list of which :setting:`INSTALLED_APPS` packages have a
  423. ``templates`` subdirectory.
  424. This loader is enabled by default.
  425. ``django.template.loaders.eggs.load_template_source``
  426. Just like ``app_directories`` above, but it loads templates from Python
  427. eggs rather than from the filesystem.
  428. This loader is disabled by default.
  429. Django uses the template loaders in order according to the
  430. :setting:`TEMPLATE_LOADERS` setting. It uses each loader until a loader finds a
  431. match.
  432. The ``render_to_string()`` shortcut
  433. ===================================
  434. To cut down on the repetitive nature of loading and rendering
  435. templates, Django provides a shortcut function which largely
  436. automates the process: ``render_to_string()`` in
  437. ``django.template.loader``, which loads a template, renders it and
  438. returns the resulting string::
  439. from django.template.loader import render_to_string
  440. rendered = render_to_string('my_template.html', { 'foo': 'bar' })
  441. The ``render_to_string`` shortcut takes one required argument --
  442. ``template_name``, which should be the name of the template to load
  443. and render -- and two optional arguments:
  444. dictionary
  445. A dictionary to be used as variables and values for the
  446. template's context. This can also be passed as the second
  447. positional argument.
  448. context_instance
  449. An instance of ``Context`` or a subclass (e.g., an instance of
  450. ``RequestContext``) to use as the template's context. This can
  451. also be passed as the third positional argument.
  452. See also the :func:`~django.shortcuts.render_to_response()` shortcut, which
  453. calls ``render_to_string`` and feeds the result into an ``HttpResponse``
  454. suitable for returning directly from a view.
  455. Configuring the template system in standalone mode
  456. ==================================================
  457. .. note::
  458. This section is only of interest to people trying to use the template
  459. system as an output component in another application. If you're using the
  460. template system as part of a Django application, nothing here applies to
  461. you.
  462. Normally, Django will load all the configuration information it needs from its
  463. own default configuration file, combined with the settings in the module given
  464. in the :setting:`DJANGO_SETTINGS_MODULE` environment variable. But if you're
  465. using the template system independently of the rest of Django, the environment
  466. variable approach isn't very convenient, because you probably want to configure
  467. the template system in line with the rest of your application rather than
  468. dealing with settings files and pointing to them via environment variables.
  469. To solve this problem, you need to use the manual configuration option described
  470. in :ref:`settings-without-django-settings-module`. Simply import the appropriate
  471. pieces of the templating system and then, *before* you call any of the
  472. templating functions, call ``django.conf.settings.configure()`` with any
  473. settings you wish to specify. You might want to consider setting at least
  474. :setting:`TEMPLATE_DIRS` (if you're going to use template loaders),
  475. :setting:`DEFAULT_CHARSET` (although the default of ``utf-8`` is probably fine)
  476. and :setting:`TEMPLATE_DEBUG`. All available settings are described in the
  477. :ref:`settings documentation <ref-settings>`, and any setting starting with
  478. ``TEMPLATE_`` is of obvious interest.