Django Variables
Dynamic data in Django templates
📦 What are Django Variables?
Django variables allow you to display dynamic data in templates. Variables are passed from views to templates and rendered using double curly braces syntax for dynamic content display.
<!-- Display a variable in Django template -->
<h1>{{ title }}</h1>
<p>Welcome, {{ username }}!</p>
Variable Basics
String Variables
Display text content
{{ name }}
Number Variables
Display numeric values
{{ age }}
List Variables
Access list items by index
{{ colors.0 }}
Dictionary Variables
Access dictionary values
{{ user.email }}
🔹 Simple Variable Example
Variables are passed from Django views to templates. Here's how to display basic variables in your template using the double curly brace syntax.
🔸 View (views.py)
from django.shortcuts import render
def home(request):
context = {
'title': 'Welcome to Django',
'username': 'John Doe'
}
return render(request, 'home.html', context)
🔸 Template (home.html)
<h1>{{ title }}</h1>
<p>Hello, {{ username }}!</p>
Output:
Welcome to Django
Hello, John Doe!
🔹 Accessing Object Attributes
Django templates use dot notation to access object attributes, dictionary keys, and list indices. This unified syntax makes templates clean and easy to read.
🔸 View
def profile(request):
context = {
'user': {
'name': 'Alice',
'email': '[email protected]',
'age': 25
}
}
return render(request, 'profile.html', context)
🔸 Template
<h2>User Profile</h2>
<p>Name: {{ user.name }}</p>
<p>Email: {{ user.email }}</p>
<p>Age: {{ user.age }}</p>
Output:
🔹 Working with Lists
Access list items using dot notation with the index number. Django templates make it simple to display specific items from lists passed through context.
🔸 View
def colors(request):
context = {
'colors': ['Red', 'Green', 'Blue']
}
return render(request, 'colors.html', context)
🔸 Template
<p>First color: {{ colors.0 }}</p>
<p>Second color: {{ colors.1 }}</p>
<p>Third color: {{ colors.2 }}</p>
Output:
First color: Red
Second color: Green
Third color: Blue
🔹 Variable Filters
Django provides filters to modify variable output. Filters are applied using the pipe symbol and can transform data like changing text case or formatting dates.
<!-- Uppercase filter -->
<p>{{ name|upper }}</p>
<!-- Lowercase filter -->
<p>{{ name|lower }}</p>
<!-- Title case filter -->
<p>{{ name|title }}</p>
<!-- Length filter -->
<p>Length: {{ name|length }}</p>
<!-- Default value if empty -->
<p>{{ description|default:"No description" }}</p>
Output (if name = "john doe"):
JOHN DOE
john doe
John Doe
Length: 8
No description
💡 Important Tips:
-
Variables are enclosed in
{{ }}double curly braces -
Use dot notation to access attributes:
{{ user.name }} -
Filters modify variable output:
{{ name|upper }} -
Chain multiple filters:
{{ text|lower|title }} - Variables that don't exist display nothing (no error)