Lesson 17 of 60 – Django Template Variables
28%

Django Template Variables

Django template variables are used to display dynamic data inside HTML templates. Data can be sent from a Django view to a template and then displayed using double curly braces such as {{ name }}.

Note: Template variables are normally provided by the view through a context dictionary. Django then makes those values available inside the template.

1. What is a Template Variable?

A template variable is a value that is passed from a Django view and displayed inside an HTML template.

<h1>{{ name }}</h1>

Here, name is a template variable.

2. Why Use Template Variables?

Template variables make HTML pages dynamic instead of displaying only fixed text.

  • Display student names
  • Display product prices
  • Display user information
  • Display database records
  • Display page titles
  • Display messages and other dynamic data

3. Basic Template Variable Syntax

Django uses double curly braces to display a variable.

{{ name }}

If the variable contains Rahul, Django displays:

Rahul

4. Creating a Variable in a View

from django.shortcuts import render

def home(request):

    data = {
        'name': 'Rahul'
    }

    return render(
        request,
        'home.html',
        data
    )

The dictionary is used to send the name value to the template.

5. Displaying a Variable in a Template

home.html

<h1>Welcome {{ name }}</h1>

If the view sends Rahul, the page displays:

Welcome Rahul

6. Context Dictionary

A context dictionary contains the data that is passed from the view to the template.

data = {
    'name': 'Rahul',
    'age': 21
}

Both values can be accessed inside the template.

7. Multiple Template Variables

View:

def profile(request):

    data = {
        'name': 'Amit',
        'age': 22,
        'city': 'Patna'
    }

    return render(
        request,
        'profile.html',
        data
    )

Template:

<h2>{{ name }}</h2>
<p>Age: {{ age }}</p>
<p>City: {{ city }}</p>

8. String Variables

A template variable can contain a string value.

data = {
    'name': 'Rahul'
}

Template:

<p>Name: {{ name }}</p>

9. Integer Variables

Template variables can also contain numbers.

data = {
    'age': 25
}

Template:

<p>Age: {{ age }}</p>

10. Decimal Variables

Numeric values such as prices can also be passed to templates.

data = {
    'price': 499.50
}

Template:

<p>Price: ₹{{ price }}</p>

11. Boolean Variables

A Boolean value can also be passed to a template.

data = {
    'is_student': True
}

Boolean values are commonly used with conditional template tags.

{% if is_student %}
    <p>This user is a student.</p>
{% endif %}

12. List Variables

A view can send a list to a template.

data = {
    'subjects': [
        'Python',
        'Django',
        'SQL'
    ]
}

The list can be displayed using a for loop.

13. Looping Through a List

{% for subject in subjects %}
    <p>{{ subject }}</p>
{% endfor %}

The loop displays every item from the subjects list.

14. Dictionary Variables

A dictionary can also be passed from a view to a template.

data = {
    'student': {
        'name': 'Rahul',
        'age': 20,
        'city': 'Patna'
    }
}

15. Accessing Dictionary Values

Django templates can use dot notation to access dictionary values.

{{ student.name }}
{{ student.age }}
{{ student.city }}

This is commonly used when displaying structured data.

16. Object Variables

A Django model object can also be passed to a template.

def student(request):

    student = Student.objects.get(id=1)

    return render(
        request,
        'student.html',
        {'student': student}
    )

17. Accessing Object Attributes

Object attributes can be displayed using dot notation.

<h1>{{ student.name }}</h1>
<p>{{ student.email }}</p>
<p>{{ student.mobile }}</p>

This is useful for displaying database records.

18. Variable with an If Condition

{% if name %}
    <h2>Hello {{ name }}</h2>
{% else %}
    <h2>Name not available</h2>
{% endif %}

A condition can check whether a value is available.

19. Default Values

The default filter can provide a value when a variable is empty or unavailable.

{{ name|default:"Guest" }}

If name does not contain a usable value, Django displays Guest.

20. Using Filters with Variables

Filters can modify the value of a template variable.

{{ name|upper }}

For example, rahul can be displayed as RAHUL.

{{ name|lower }}

The lower filter converts text to lowercase.

21. Using a Variable in an HTML Attribute

A template variable can also be used inside an HTML attribute.

<img src="{{ image_url }}" alt="{{ name }}">

The actual values are supplied by the Django view.

22. Variable Inside a Link

<a href="{{ website }}">
    Visit Website
</a>

The website variable can contain the destination URL.

23. Passing Database Records

Views often retrieve multiple records from a database and pass them to templates.

def students(request):

    students = Student.objects.all()

    return render(
        request,
        'students.html',
        {'students': students}
    )

The template can then display the records using a loop.

24. Displaying Database Records

{% for student in students %}

    <h3>{{ student.name }}</h3>
    <p>{{ student.email }}</p>

{% endfor %}

Each database record can be displayed using its attributes.

25. Nested Variables

Variables can contain nested dictionaries or objects.

data = {
    'student': {
        'name': 'Amit',
        'course': 'Python',
        'city': 'Patna'
    }
}

Template:

{{ student.name }}
{{ student.course }}
{{ student.city }}

26. Missing Variables

If a variable is not available in the template context, Django generally renders an empty string when the variable is accessed directly.

<p>{{ unknown_variable }}</p>

It is therefore important to use the correct variable names in both the view and template.

27. Variable Naming

Use meaningful names for template variables.

student_name
course_name
product_price
user_email

Meaningful names make templates easier to understand and maintain.

28. Common Template Variable Mistakes

  • Using the wrong variable name
  • Forgetting to pass the variable from the view
  • Using incorrect curly braces
  • Confusing template variables with template tags
  • Trying to access an unavailable object attribute
  • Forgetting to include the correct context data
Correct:
{{ name }}

Incorrect:
{ name }

29. Complete Template Variable Example

views.py

from django.shortcuts import render

def profile(request):

    data = {
        'name': 'Rahul',
        'age': 21,
        'course': 'Django',
        'city': 'Patna'
    }

    return render(
        request,
        'profile.html',
        data
    )

profile.html

<h1>Student Profile</h1>

<p>Name: {{ name }}</p>
<p>Age: {{ age }}</p>
<p>Course: {{ course }}</p>
<p>City: {{ city }}</p>

30. Summary of Django Template Variables

Template variables are an important part of Django's template system. They allow a view to send dynamic information to an HTML page.

  • Variables are displayed using {{ variable }}.
  • Views send variables through a context dictionary.
  • Strings, numbers, lists, dictionaries, and objects can be passed.
  • Dot notation can access dictionary values and object attributes.
  • Variables can be used with template filters.
  • Variables can be used with conditions and loops.
  • Database records can be passed to templates.
  • Meaningful variable names make templates easier to maintain.

📌 Key Points

  • Django template variables display dynamic data in HTML.
  • Use {{ variable }} to display a value.
  • Variables are normally passed from views using a context dictionary.
  • Lists can be displayed using for loops.
  • Dictionary values and object attributes can be accessed with dot notation.
  • Template filters can modify variable output.
  • Database records can be displayed using template variables.
  • Correct variable names are important when connecting views and templates.

🧠 Quick Quiz

Question: Which syntax is used to display a variable in a Django template?