TExcelTAD
Home › Django › Django Template Variables

Django Template Variables

A variable in a template is written {{ name }}. When the template is rendered, Django looks the name up in the context — the dictionary your view passes to render() — and prints the result, HTML-escaped. Variables can reach into dictionaries, object attributes, list items and even call methods, all with the same dot syntax.

Context data from a view

The view decides what data the template receives:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
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", {
                    "profile.html": "<h1>{{ first_name }} {{ last_name }}</h1>\n<p>Age: {{ age }}</p>",
                })]}}],
)
django.setup()
from django.shortcuts import render
from django.urls import path
from django.test import Client

def profile(request):
    context = {"first_name": "Ngoc", "last_name": "Vu", "age": 29}
    return render(request, "profile.html", context)

urls.urlpatterns = [path("me/", profile)]
print(Client().get("/me/").content.decode())
<h1>Ngoc Vu</h1>
<p>Age: 29</p>

The dot lookup

Templates have no [] or () syntax. The single dot does everything, trying these lookups in order until one works:

Order Lookup {{ x.y }} means
1 dictionary key x["y"]
2 attribute or method x.y — and if it's callable, x.y()
3 list index x[y] when y is a number, e.g. {{ items.0 }}
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

class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

    def reading_hours(self):
        return self.pages // 40

source = """dict key:     {{ user.name }}
attribute:    {{ book.title }}
method call:  {{ book.reading_hours }} hours
list index:   {{ colors.0 }} / {{ colors.2 }}
nested:       {{ shop.owner.city }}
str method:   {{ book.title.upper }}"""

context = Context({
    "user": {"name": "Phuong"},
    "book": Book("The Hobbit", 310),
    "colors": ["red", "green", "blue"],
    "shop": {"owner": {"city": "Can Tho"}},
})
print(Template(source).render(context))
dict key:     Phuong
attribute:    The Hobbit
method call:  7 hours
list index:   red / blue
nested:       Can Tho
str method:   THE HOBBIT

Methods are called without arguments — you can't pass arguments to a method from a template. If you need that, compute the value in the view or write a custom filter.

Missing variables fail silently

A variable that doesn't exist renders as an empty string. Templates are designed not to crash a page because of a typo — use the default filter to show something useful instead:

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

t = Template("[{{ nickname }}] [{{ user.phone }}] [{{ nickname|default:'anonymous' }}]")
print(t.render(Context({"user": {"name": "Hai"}})))

t2 = Template("Items: {{ items|length }}, first: {{ items.0|default:'none' }}")
print(t2.render(Context({"items": []})))
[] [] [anonymous]
Items: 0, first: none

Tip: During development you can set "string_if_invalid": "MISSING(%s)" in the template OPTIONS to make typos visible. Don't leave it on in production.

Model objects as variables

Model instances work exactly like other objects: fields are attributes, methods are called, and {{ book }} prints the model's __str__():

python · try it yourself
import django
from django.conf import settings
settings.configure(
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}],
)
django.setup()
from django.db import models, connection
from django.template import Template, Context

class Member(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    level = models.CharField(max_length=1, choices=[("B", "Bronze"), ("G", "Gold")])

    class Meta:
        app_label = "demo"

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

with connection.schema_editor() as editor:
    editor.create_model(Member)
Member.objects.create(first_name="Kim", last_name="Do", level="G")

t = Template("{{ m }} (#{{ m.id }}) is a {{ m.get_level_display }} member; code {{ m.level }}.")
print(t.render(Context({"m": Member.objects.get(pk=1)})))
Kim Do (#1) is a Gold member; code G.

Setting variables inside the template: with

Occasionally you want a short name for a long expression, or to avoid repeating an expensive method call. {% with %} creates a variable that exists until {% endwith %}:

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

t = Template(
    "{% with total=order.items|length name=order.customer.name %}"
    "{{ name }} ordered {{ total }} item{{ total|pluralize }}."
    "{% endwith %}"
)
order = {"customer": {"name": "Uyen"}, "items": ["pen", "ink", "paper"]}
print(t.render(Context({"order": order})))
Uyen ordered 3 items.

Variables everywhere: context processors

Some variables, such as request, user and messages, appear in every template even though your view never passes them. They come from context processors listed in TEMPLATES["OPTIONS"]["context_processors"], which only run when the template is rendered with a request (as render() does).

Context processor Adds
django.template.context_processors.request request
django.contrib.auth.context_processors.auth user, perms
django.contrib.messages.context_processors.messages messages
django.template.context_processors.debug debug, sql_queries (when DEBUG and internal IP)

Test yourself

What does {{ colors.1 }} print when colors = ["red", "green"]?

  1. red
  2. green
  3. colors.1
  4. An error

What happens when a template uses a variable that isn't in the context?

  1. The page raises an exception
  2. It prints None
  3. It renders as an empty string
  4. It prints the variable name

How do you call book.reading_hours() in a template?

  1. {{ book.reading_hours() }}
  2. {{ book.reading_hours }}
  3. {% call book.reading_hours %}
  4. It's not possible