← Back to Django, page 1

django-0008 · Easy fresher

How do Django templates work? Explain variables, filters, tags, template inheritance and auto-escaping.

Django templates use {{ variable }} to print values, filters like {{ name|upper }} to transform them, and tags like {% for %} and {% if %} for logic. Inheritance lets a base.html define {% block %} sections that child templates fill with {% extends %}. Output is HTML-escaped by default, which blocks most XSS.

Full answer

The Django Template Language (DTL) is deliberately limited. It shows data; it does not run arbitrary Python. Heavy logic belongs in views or models.

Building blocks:

  • Variables: {{ student.name }}. The dot tries a dictionary key, then an attribute, then a list index. A callable with no arguments is called. Missing values print as an empty string (controlled by string_if_invalid).
  • Filters: {{ marks|default:"absent" }}, {{ name|title }}, {{ fee|floatformat:2 }}, {{ joined|date:"d M Y" }}, {{ items|length }}. Filters chain left to right.
  • Tags: {% if %}, {% for s in students %}...{% empty %}...{% endfor %}, {% url 'name' %}, {% csrf_token %}, {% include "row.html" %}, {% with %}.
  • Comments: {# short #} and {% comment %}...{% endcomment %}.

Inheritance avoids copying the same header and footer into every page. base.html defines blocks:

<title>{% block title %}College{% endblock %}</title> <main>{% block content %}{% endblock %}</main>

A child starts with {% extends "base.html" %} and overrides only the blocks it needs. {{ block.super }} keeps the parent's content and adds to it.

Auto-escaping turns <, >, &, quotes into HTML entities, so a student named <script> shows as text and does not run. Only switch escaping off with |safe or mark_safe() for content you created or sanitised yourself.

Templates are found through the TEMPLATES setting: DIRS for project-level folders and APP_DIRS=True for each app's templates/ folder. Namespacing as templates/students/list.html avoids two apps clashing on list.html.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.template import engines

settings.TEMPLATES = [{
    "BACKEND": "django.template.backends.django.DjangoTemplates",
    "OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
        "base.html": "<h1>{% block title %}College{% endblock %}</h1>{% block content %}{% endblock %}",
        "results.html": (
            "{% extends 'base.html' %}"
            "{% block title %}{{ block.super }} results{% endblock %}"
            "{% block content %}<ul>{% for s in students %}"
            "<li>{{ s.name|title }}: {{ s.marks|default:'absent' }}</li>"
            "{% empty %}<li>No students</li>{% endfor %}</ul>{% endblock %}"
        ),
    })]},
}]

django_engine = engines["django"]
html = django_engine.get_template("results.html").render({
    "students": [
        {"name": "asha rao", "marks": 91},
        {"name": "<script>alert(1)</script>", "marks": None},
    ]
})
print(html)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): <h1>College results</h1><ul><li>Asha Rao: 91</li><li>&lt;Script&gt;Alert(1)&lt;/Script&gt;: absent</li></ul>

Key points

  • {{ }} prints, |filters transform, {% %} tags control flow
  • {% extends %} and {% block %} give layout reuse
  • Auto-escaping is on by default and prevents XSS
  • Only use |safe on trusted content
  • Keep business logic out of templates

Common mistakes

  • Writing complex logic in templates instead of preparing data in the view
  • Marking user input as safe
  • Copy-pasting header HTML into every template instead of using inheritance
  • Putting all templates in a flat folder so two apps clash on the same file name

Follow-ups

  • How do you write a custom template filter?
  • What is a context processor?
  • How is {% include %} different from {% extends %}?

Tips

  • Show a tiny base/child example from memory
  • Say that auto-escaping is on by default and what it protects against
  • Mention that DTL limits logic on purpose