Skip to main content

Django Template Variables

In Django web development, template variables are one of the most fundamental concepts that allow you to display dynamic data in your HTML templates. They form the bridge between your Python code and what your users see in their browsers.

What Are Template Variables?

Template variables in Django allow you to insert dynamic values into your HTML templates. These values are passed from your views to the templates during rendering. Variables are surrounded by double curly braces {{ }} in Django templates.

Basic Variable Syntax

When you want to display a variable in a Django template, you use the following syntax:

django
<p>Hello, {{ name }}!</p>

If the name variable has a value of "Django User" when the template is rendered, the output HTML would be:

html
<p>Hello, Django User!</p>

Passing Variables to Templates

To use variables in templates, you need to pass them from your views. Here's how:

python
# In your views.py file
from django.shortcuts import render

def greeting_view(request):
context = {
'name': 'Django User',
'language': 'Python',
'framework': 'Django',
}
return render(request, 'greeting.html', context)
django
<!-- In greeting.html template -->
<h1>Welcome!</h1>
<p>Hello, {{ name }}!</p>
<p>You are learning {{ language }} with the {{ framework }} framework.</p>

When rendered, this template will output:

html
<h1>Welcome!</h1>
<p>Hello, Django User!</p>
<p>You are learning Python with the Django framework.</p>

Accessing Dictionary Values and Object Attributes

Django template variables can access dictionary keys, object attributes, and methods using dot notation:

Dictionary Keys

python
# In views.py
def user_profile(request):
context = {
'user_data': {
'name': 'John Smith',
'email': '[email protected]',
'role': 'Developer'
}
}
return render(request, 'profile.html', context)
django
<!-- In profile.html -->
<p>Name: {{ user_data.name }}</p>
<p>Email: {{ user_data.email }}</p>
<p>Role: {{ user_data.role }}</p>

Object Attributes

For objects, the syntax is the same:

python
# In views.py
from django.contrib.auth.models import User

def user_detail(request):
user = User.objects.get(username='admin')
return render(request, 'user_detail.html', {'user': user})
django
<!-- In user_detail.html -->
<p>Username: {{ user.username }}</p>
<p>Email: {{ user.email }}</p>
<p>Date joined: {{ user.date_joined }}</p>

Working with Lists and Indexing

Django templates also support accessing items in lists by their index:

python
# In views.py
def fruits_view(request):
context = {
'fruits': ['Apple', 'Banana', 'Cherry', 'Date']
}
return render(request, 'fruits.html', context)
django
<!-- In fruits.html -->
<p>First fruit: {{ fruits.0 }}</p>
<p>Second fruit: {{ fruits.1 }}</p>
<p>Last fruit: {{ fruits.3 }}</p>

Output:

html
<p>First fruit: Apple</p>
<p>Second fruit: Banana</p>
<p>Last fruit: Date</p>

Variable Filters

Django provides filters to modify variable values in templates. Filters are applied using the pipe character (|):

django
<!-- Capitalize the first letter -->
<p>{{ name|title }}</p>

<!-- Convert text to lowercase -->
<p>{{ text|lower }}</p>

<!-- Format date -->
<p>{{ today|date:"Y-m-d" }}</p>

<!-- Default value if variable is empty -->
<p>{{ user_name|default:"Guest" }}</p>

Here's an example in a view:

python
# In views.py
from datetime import datetime

def filter_demo(request):
context = {
'name': 'john doe',
'text': 'THIS IS SOME TEXT',
'today': datetime.now(),
'user_name': '',
'description': 'Django is a high-level Python web framework.',
}
return render(request, 'filters.html', context)
django
<!-- In filters.html -->
<p>Name (title): {{ name|title }}</p>
<p>Text (lowercase): {{ text|lower }}</p>
<p>Date: {{ today|date:"F j, Y" }}</p>
<p>User: {{ user_name|default:"Guest" }}</p>
<p>Description (truncated): {{ description|truncatechars:20 }}</p>

Output:

html
<p>Name (title): John Doe</p>
<p>Text (lowercase): this is some text</p>
<p>Date: July 15, 2023</p>
<p>User: Guest</p>
<p>Description (truncated): Django is a high-le...</p>

Using Variables in Conditionals and Loops

Variables can also be used in template tags for conditionals and loops:

Conditionals

django
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% else %}
<p>Please log in</p>
{% endif %}

Loops

django
<ul>
{% for item in shopping_list %}
<li>{{ item }}</li>
{% empty %}
<li>No items in the list</li>
{% endfor %}
</ul>

Real-World Example: Product Listing

Let's look at a more comprehensive example for an e-commerce product listing:

python
# In views.py
def product_list(request):
products = [
{
'id': 1,
'name': 'Smartphone',
'price': 699.99,
'in_stock': True,
'features': ['5G', 'Dual camera', 'Fast charging']
},
{
'id': 2,
'name': 'Laptop',
'price': 1299.99,
'in_stock': False,
'features': ['16GB RAM', 'SSD', '4K display']
},
{
'id': 3,
'name': 'Headphones',
'price': 199.99,
'in_stock': True,
'features': ['Noise cancelling', 'Bluetooth', 'Long battery life']
}
]
return render(request, 'products/list.html', {'products': products})
django
<!-- In products/list.html -->
<h1>Our Products</h1>

<div class="product-grid">
{% for product in products %}
<div class="product-card">
<h2>{{ product.name }}</h2>
<p class="price">${{ product.price|floatformat:2 }}</p>

{% if product.in_stock %}
<span class="badge badge-success">In Stock</span>
{% else %}
<span class="badge badge-danger">Out of Stock</span>
{% endif %}

<h3>Features:</h3>
<ul>
{% for feature in product.features %}
<li>{{ feature }}</li>
{% endfor %}
</ul>

<a href="{% url 'product_detail' product.id %}" class="btn">View Details</a>
</div>
{% empty %}
<p>No products available.</p>
{% endfor %}
</div>

Common Mistakes and Troubleshooting

  1. Missing or misspelled variables: If you try to access a variable that doesn't exist or is misspelled, Django will render an empty string rather than raising an error.

  2. Using Python syntax: Remember that Django template language is not Python. For example, you can't use function calls with arguments in templates directly.

    django
    <!-- This won't work -->
    {{ my_function(arg1, arg2) }}

    <!-- Instead, create a custom template filter or pass the result from the view -->
  3. Forgetting to use the dot notation: Use the dot notation to access attributes, not square brackets like in Python.

    django
    <!-- Correct -->
    {{ user.email }}

    <!-- Incorrect - won't work -->
    {{ user['email'] }}

Summary

Django template variables provide a powerful way to display dynamic data in your HTML templates. They can:

  • Display simple values passed from views
  • Access dictionary keys and object attributes using dot notation
  • Work with lists using indexing
  • Be modified with filters
  • Be used in conditional statements and loops

When working with Django templates, remember that variables are enclosed in double curly braces {{ }}, and you use dot notation to access attributes and dictionary keys.

Practice Exercises

  1. Create a Django view that passes your name, age, and hobbies (as a list) to a template, then display them using template variables.

  2. Make a template that displays a list of books with their titles, authors, and publication years. Use template variables and the date filter for formatting.

  3. Create a template that shows user information differently depending on whether the user is a staff member or not, using conditionals with variables.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)