TExcelTAD
Home › Django › Django Templates

Django Templates

Building HTML with Python string concatenation quickly becomes unreadable. Django's template language lets you write normal HTML files with a few placeholders and tags, and fill them with data from your view. Templates deliberately contain presentation logic only — the heavy lifting stays in Python.

Where templates live

By convention each app keeps its templates in <app>/templates/<app>/, which avoids name clashes between apps:

text
books/
├── templates/
│   └── books/
│       ├── book_list.html
│       └── book_detail.html
└── views.py

With "APP_DIRS": True in the TEMPLATES setting (the startproject default), Django finds them automatically.

python
# settings.py (generated by startproject)
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],   # optional project-wide folder
        "APP_DIRS": True,
        "OPTIONS": {"context_processors": [...]},
    },
]

The syntax in one table

Syntax Name Example
{{ ... }} variable {{ book.title }}
{% ... %} tag (logic) {% for b in books %} … {% endfor %}
{{ x|filter }} filter {{ name|upper }}
{# ... #} comment {# not shown #}

Rendering a template string

The quickest way to experiment is Template + Context:

python · try it yourself
import django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context

template = Template("Hello {{ name }}! You have {{ count }} new message{{ count|pluralize }}.")
print(template.render(Context({"name": "Mai", "count": 1})))
print(template.render(Context({"name": "Quan", "count": 4})))
Hello Mai! You have 1 new message.
Hello Quan! You have 4 new messages.

A compiled Template can be rendered many times with different contexts.

Template files and render()

In a project, a view calls the render() shortcut with the template name; Django searches its loaders, renders it with the context dictionary, and wraps the result in an HttpResponse. In the playground we use the locmem loader, which reads templates from a dictionary instead of from disk:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
TEMPLATE_FILES = {
    "books/book_list.html": """<h1>{{ heading }}</h1>
<ul>
{% for book in books %}  <li>{{ book.title }} ({{ book.year }})</li>
{% endfor %}</ul>""",
}
settings.configure(
    SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
    TEMPLATES=[{
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", TEMPLATE_FILES)]},
    }],
)
django.setup()
from django.shortcuts import render
from django.urls import path
from django.test import Client

def book_list(request):
    books = [{"title": "Dune", "year": 1965}, {"title": "Emma", "year": 1815}]
    return render(request, "books/book_list.html", {"heading": "My books", "books": books})

urls.urlpatterns = [path("books/", book_list)]
print(Client().get("/books/").content.decode())
<h1>My books</h1>
<ul>
  <li>Dune (1965)</li>
  <li>Emma (1815)</li>
</ul>

render_to_string and get_template

Sometimes you want the HTML as a string — for an email body, for example. render_to_string() does exactly what render() does without building a response:

python · try it yourself
import django
from django.conf import settings
settings.configure(TEMPLATES=[{
    "BACKEND": "django.template.backends.django.DjangoTemplates",
    "OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
        "emails/welcome.txt": "Hi {{ user }},\nwelcome to {{ site|default:'our site' }}!",
    })]},
}])
django.setup()
from django.template.loader import render_to_string, get_template

print(render_to_string("emails/welcome.txt", {"user": "Tam", "site": "Bookshelf"}))
print("---")
t = get_template("emails/welcome.txt")
print(t.render({"user": "Lan"}))
Hi Tam,
welcome to Bookshelf!
---
Hi Lan,
welcome to our site!

Note that get_template() returns a backend template whose render() takes a plain dict, while django.template.Template (used earlier) takes a Context.

Automatic HTML escaping

Any value printed with {{ }} is escaped: <, >, &, ' and " become HTML entities. This stops users from injecting scripts into your pages (XSS):

python · try it yourself
import django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context

comment = '<script>alert("hacked")</script>'
print(Template("<p>{{ comment }}</p>").render(Context({"comment": comment})))
print(Template("<p>{{ comment|safe }}</p>").render(Context({"comment": "<b>trusted</b>"})))
<p>&lt;script&gt;alert(&quot;hacked&quot;)&lt;/script&gt;</p>
<p><b>trusted</b></p>

Note: Only mark content as safe when you created it yourself. User input should always be escaped.

Upcoming lessons cover variables, tags, inheritance and filters in depth.

Test yourself

Which syntax outputs a variable in a Django template?

  1. {% name %}
  2. {{ name }}
  3. ${name}
  4. <%= name %>

Where does Django look for an app's templates when APP_DIRS is True?

  1. <app>/templates/
  2. <app>/static/
  3. <project>/settings/
  4. Only in DIRS

What does {{ comment }} print if comment is <b>hi</b>?

  1. hi in bold
  2. &lt;b&gt;hi&lt;/b&gt;
  3. Nothing
  4. An error