5️⃣ 🧾 Django Template Syntax & Tags
Estimated reading: 3 minutes 31 views

💡 Django Variables – Display Dynamic Data in Templates (2025 Guide)

🧲 Introduction – What Are Variables in Django Templates?

Django variables allow you to insert dynamic content into HTML pages using the Django templating engine. These variables are passed from views to templates and rendered using the {{ variable }} syntax.

🎯 In this guide, you’ll learn:

  • How to define and pass variables to templates
  • How to display and filter variables
  • How to use object attributes and dictionary keys
  • Best practices for safe and clean variable rendering

📦 Step 1: Pass Variables from View to Template

views.py

from django.shortcuts import render

def profile_view(request):
    context = {
        'name': 'John Doe',
        'age': 30,
        'email': 'john@example.com',
    }
    return render(request, 'profile.html', context)

✅ The dictionary context makes name, age, and email available in the template.


🧾 Step 2: Use Variables in Templates

profile.html

<h1>User Profile</h1>
<p>Name: {{ name }}</p>
<p>Age: {{ age }}</p>
<p>Email: {{ email }}</p>

✅ This will render:

Name: John Doe
Age: 30
Email: john@example.com

🔍 Accessing Object Attributes and Dictionary Keys

➤ From Model Object

context = {'user': user}  # user is a model instance
<p>Username: {{ user.username }}</p>
<p>Joined: {{ user.date_joined|date:"F j, Y" }}</p>

➤ From Dictionary

context = {'person': {'name': 'Alice', 'age': 28}}
<p>{{ person.name }}</p>
<p>{{ person.age }}</p>

🧠 Using Filters with Variables

Django offers built-in filters to transform variable output:

{{ name|upper }}         <!-- JOHN DOE -->
{{ bio|linebreaks }}     <!-- Adds <br> for new lines -->
{{ date_joined|date:"Y-m-d" }} <!-- Formats date -->
{{ price|floatformat:2 }} <!-- 10 ➝ 10.00 -->

📛 Handling Missing or Empty Variables

Use the default filter to avoid blank output:

{{ username|default:"Guest" }}

Use {% if variable %} to check before rendering:

{% if email %}
  <p>Email: {{ email }}</p>
{% else %}
  <p>No email provided</p>
{% endif %}

✅ Best Practices

  • ✅ Always escape unsafe input (Django does this by default)
  • ✅ Use default, length, or join filters for readable output
  • ✅ Avoid exposing sensitive variables (like passwords or tokens)
  • ✅ Keep logic minimal—compute values in views, not templates

📌 Summary – Recap & Next Steps

🔍 Key Takeaways:

  • Use {{ variable }} to display dynamic data in templates
  • Pass variables using the context dictionary in views
  • Access object fields and dictionary keys with dot notation
  • Enhance output using built-in template filters

⚙️ Real-World Relevance:
Django variables allow you to build dynamic dashboards, profiles, listings, and content-driven websites by inserting logic-free data directly into HTML.


❓ Frequently Asked Questions (FAQ)

❓ What if a variable is missing in the template?

✅ It renders as a blank by default. Use |default:"value" to avoid empty output.


❓ Can I use functions as variables?

✅ You can access methods that return strings:

{{ user.get_full_name }}

If the method requires parentheses, it won’t work directly in templates.


❓ Can I pass multiple variables to a template?

✅ Yes. Just include them all in the context dictionary.


❓ Are variables safe from XSS?

✅ Yes, Django automatically escapes HTML. Use |safe only if you’re confident the content is secure.


❓ Can I loop through variables?

✅ Yes. Example:

{% for item in items %}
  <li>{{ item.name }}</li>
{% endfor %}

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Django Variables

Or Copy Link

CONTENTS
Scroll to Top