Skip to content
Kuza Ndoto Academy

Django Templates

IntermediateChapter 3 · Page 9 of 234 min readUpdated 15 Nov 2026

Django templates are HTML files with special placeholders. A view passes data to a template, and the template engine fills in the placeholders to produce the final page. This keeps your Python logic and your HTML neatly separate.

Where templates live

The TEMPLATES setting tells Django where to look. With "APP_DIRS": True (the default), Django searches a templates/ folder inside every installed app. Adding a project-wide folder to DIRS is useful for shared layouts:

campus/settings.py

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

Our event templates go in events/templates/events/, and the view refers to them as "events/event_list.html".

The three building blocks

SyntaxNamePurpose
{{ ... }}VariablePrint a value
{% ... %}TagLogic: loops, conditions, links, loading libraries
{{ value|filter }}FilterTransform a value before printing it

Comments use {# one line #} or {% comment %} ... {% endcomment %} and never reach the browser.

A complete example

Let's give our pretend events from the Writing Views page a date and a description:

events/views.py

from datetime import date

from django.shortcuts import render

EVENTS = [
    {"id": 1, "title": "Freshers' Welcome Night", "venue": "Main Hall",
     "date": date(2026, 11, 20), "capacity": 300,
     "description": "A night of music, food and games for new students."},
    {"id": 2, "title": "Campus Hackathon", "venue": "ICT Lab 2",
     "date": date(2026, 11, 28), "capacity": 60,
     "description": "Build an app that solves a problem in your county in 24 hours."},
    {"id": 3, "title": "Career Fair", "venue": "Main Hall",
     "date": date(2026, 12, 2), "capacity": 500, "description": ""},
]


def event_list(request):
    return render(request, "events/event_list.html", {"events": EVENTS})

events/templates/events/event_list.html

<h1>Upcoming events</h1>
<p>{{ events|length }} event{{ events|length|pluralize }} this term.</p>

<ol>
  {% for event in events %}
    <li>
      <a href="{% url 'events:event_detail' event.id %}">{{ event.title }}</a>
      ({{ event.date|date:"D j M Y" }}, {{ event.venue }})
      {% if event.capacity >= 300 %}<strong>Big event!</strong>{% endif %}
      <br>{{ event.description|default:"No description yet."|truncatewords:5 }}
    </li>
  {% empty %}
    <li>No events yet. Check back soon.</li>
  {% endfor %}
</ol>

This is what the visitor sees in the browser:

Upcoming events 3 events this term. 1. Freshers' Welcome Night (Fri 20 Nov 2026, Main Hall) Big event! A night of music, food … 2. Campus Hackathon (Sat 28 Nov 2026, ICT Lab 2) Build an app that solves … 3. Career Fair (Wed 2 Dec 2026, Main Hall) Big event! No description yet.

Inside a loop, {{ forloop.counter }} gives the current position (starting at 1), which is handy when you aren't using a numbered list.

Variables and the dot

The dot in {{ event.title }} is flexible. Django tries, in order: a dictionary key (event["title"]), an attribute (event.title) and a list index (events.0). If the result is callable, Django calls it with no arguments, so {{ event.get_absolute_url }} works without brackets. A variable that doesn't exist prints as an empty string instead of crashing.

Common tags

  • {% if %}, {% elif %}, {% else %}: support and, or, not, in and comparisons such as == and <.
  • {% for item in list %} ... {% empty %} ... {% endfor %}: the {% empty %} part runs when the list has no items. Inside the loop, forloop.first and forloop.last are handy for styling.
  • {% url 'name' args %}: builds a link from a URL name (see URL Routing).
  • {% csrf_token %}: required inside every POST form.
  • {% load static %} and {% static 'path' %}: link to CSS and images (see Static Files).

Useful filters

FilterExampleResult
upper / lower / title{{ "main hall"|title }}Main Hall
length{{ events|length }}3
default{{ ""|default:"TBC" }}TBC
date{{ event.date|date:"j F Y" }}20 November 2026
truncatewords{{ text|truncatewords:5 }}First five words then …
pluralizeevent{{ 1|pluralize }}event
floatformat{{ 1499.5|floatformat:2 }}1499.50
linebreaks{{ event.description|linebreaks }}Wraps paragraphs in <p> tags

Automatic escaping keeps you safe

Django escapes every variable by default, turning characters like < into &lt;. If a user types a malicious comment such as <script>alert('hi')</script>, the template sends it to the browser as harmless text:

&lt;script&gt;alert(&#x27;hi&#x27;)&lt;/script&gt;

This protects your site against cross-site scripting (XSS) attacks.

Warning

The |safe filter and {% autoescape off %} switch escaping off. Only use them on HTML that you wrote and trust, never on anything a user typed.

Common mistake

Trying to call methods with arguments, as in {{ event.price_for(student) }}. Templates deliberately can't do this. Calculate the value in the view or a model method and pass it in the context instead.

If Django raises TemplateDoesNotExist, the error page lists every folder it searched. The usual causes are a missing app in INSTALLED_APPS, a typo in the file name, or forgetting the inner events/ folder.

Key points

  • Use {{ }} for variables, {% %} for tags and | for filters.
  • Keep app templates in app/templates/app/ and shared ones in a project templates/ folder.
  • {% for %} with {% empty %} and {% if %} handle most display logic.
  • Variables are auto-escaped; only mark trusted content as safe.
Up next · TemplatesTemplate InheritanceShare layouts across pages.
→

Tip: use the ← and → keys to move between pages.