Django Template Variables

Template variables let you drop Python values from your view's context straight into HTML using the {{ variable }} syntax.

The {{ variable }} Syntax

Every value you output in a Django template comes from the context — a dictionary the view passes to render(). The template engine looks up each name inside {{ }} against that context and writes the result into the HTML, automatically escaping special characters like < and & to prevent injection.

Where Variables Come From

A view builds a context dictionary and hands it to render(request, template_name, context). Every key in that dictionary becomes a variable name the template can reference with double curly braces.

Example

# views.py
def profile(request):
    context = {
        'username': 'grace',
        'age': 29,
    }
    return render(request, 'profile.html', context)


<!-- profile.html -->
<h1>Hello, {{ username }}!</h1>
<p>You are {{ age }} years old.</p>

Dot Notation Lookup

Templates deliberately don't support Python's mixed syntax of brackets, parentheses, and dots. Instead, a single dot does all the work. For an expression like a.b, Django tries, in order: a dictionary lookup a['b'], then an attribute lookup a.b, then a list-index lookup a[b] when b is an integer, and finally a method call a.b() as long as the method takes no required arguments.

Example

<!-- profile.html -->
<p>Name: {{ user.name }}</p>          <!-- dictionary key lookup -->
<p>First role: {{ user.roles.0 }}</p>  <!-- list index lookup -->
<p>Today: {{ today.year }}</p>         <!-- attribute lookup on a date object -->
<p>Weekday: {{ today.isoweekday }}</p> <!-- method call, no arguments -->

Example

<!-- profile.html -->
{{ user.profile.bio|default:'No bio yet.' }}
{{ user.nickname|default:'Anonymous' }}
{{ request.GET.page|default:'1' }}
  • Dictionary key — {{ user.name }} tries user['name'] first
  • Attribute lookup — falls back to user.name as a Python attribute
  • List or tuple index — {{ items.0 }} returns items[0], never items[-1]
  • Method call — {{ today.isoweekday }} calls the method only if it takes no required arguments
ExpressionWhat Django Tries, In Order
{{ person.name }}dict key person['name'], then attribute person.name
{{ items.0 }}list index items[0] — dot notation is the only way to index in templates
{{ article.get_absolute_url }}method call article.get_absolute_url() with zero arguments
Note: If a variable or attribute doesn't exist, Django renders it as an empty string instead of raising an error. This keeps templates from crashing on optional data, but it also means a typo like {{ usre.name }} fails silently — check spelling first when a value appears blank.

Exercise: Django Template Variables

Which syntax outputs the value of a variable in a Django template?