Django If Else
Conditional logic in Django templates
🔀 What is Django If Else?
Django if else statements enable conditional rendering in templates. Display different content based on conditions, making your templates dynamic and responsive to various data states and user scenarios.
<!-- Basic if statement -->
{% if user.is_logged_in %}
<p>Welcome back!</p>
{% endif %}
Conditional Statements
if
Execute code if condition is true
{% if condition %}
...
{% endif %}
else
Execute code if condition is false
{% if condition %}
...
{% else %}
...
{% endif %}
elif
Check multiple conditions
{% if condition1 %}
...
{% elif condition2 %}
...
{% endif %}
Operators
Compare values in conditions
==, !=, <, >
<=, >=
and, or, not
🔹 Simple If Statement
The basic if statement checks a condition and displays content only when the condition evaluates to true. This is the foundation of conditional rendering in templates.
🔸 View
def home(request):
context = {
'is_logged_in': True,
'username': 'Alice'
}
return render(request, 'home.html', context)
🔸 Template
{% if is_logged_in %}
<h2>Welcome back, {{ username }}!</h2>
<p>You are logged in.</p>
{% endif %}
Output:
Welcome back, Alice!
You are logged in.
🔹 If Else Statement
The if else statement provides an alternative when the condition is false. Display different content based on whether the condition passes or fails for complete control.
🔸 View
def profile(request):
context = {
'is_premium': False
}
return render(request, 'profile.html', context)
🔸 Template
{% if is_premium %}
<div class="premium-badge">
<h3>⭐ Premium Member</h3>
<p>Enjoy all premium features!</p>
</div>
{% else %}
<div class="free-badge">
<h3>Free Member</h3>
<p>Upgrade to premium for more features.</p>
</div>
{% endif %}
Output:
Free Member
Upgrade to premium for more features.
🔹 If Elif Else Statement
Use elif to check multiple conditions sequentially. Django evaluates each condition in order and executes the first matching block, perfect for handling multiple scenarios efficiently.
🔸 View
def dashboard(request):
context = {
'score': 85
}
return render(request, 'dashboard.html', context)
🔸 Template
{% if score >= 90 %}
<p class="grade">Grade: A - Excellent!</p>
{% elif score >= 80 %}
<p class="grade">Grade: B - Good job!</p>
{% elif score >= 70 %}
<p class="grade">Grade: C - Fair</p>
{% else %}
<p class="grade">Grade: F - Need improvement</p>
{% endif %}
Output:
Grade: B - Good job!
🔹 Comparison Operators
Django templates support various comparison operators for building conditions. Use these operators to compare values and create sophisticated conditional logic in your templates.
<!-- Equal to -->
{% if age == 18 %}
<p>You are exactly 18 years old.</p>
{% endif %}
<!-- Not equal to -->
{% if status != "pending" %}
<p>Status is not pending.</p>
{% endif %}
<!-- Greater than -->
{% if price > 100 %}
<p>Expensive item</p>
{% endif %}
<!-- Less than or equal to -->
{% if quantity <= 5 %}
<p>Low stock warning!</p>
{% endif %}
🔹 Logical Operators
Combine multiple conditions using logical operators. The and, or, and not operators allow you to create complex conditional statements for advanced template logic.
🔸 AND Operator
{% if is_logged_in and is_premium %}
<p>Access granted to premium content</p>
{% endif %}
🔸 OR Operator
{% if is_admin or is_moderator %}
<p>You have moderation privileges</p>
{% endif %}
🔸 NOT Operator
{% if not is_banned %}
<p>Welcome to the community!</p>
{% endif %}
🔸 Combined Operators
{% if age >= 18 and country == "USA" or has_permission %}
<p>Access granted</p>
{% endif %}
🔹 Checking Variable Existence
Check if variables exist or have values before using them. This prevents errors and allows graceful handling of missing or empty data in your templates.
<!-- Check if variable exists -->
{% if username %}
<p>Hello, {{ username }}!</p>
{% else %}
<p>Hello, Guest!</p>
{% endif %}
<!-- Check if list is not empty -->
{% if items %}
<p>You have {{ items|length }} items</p>
{% else %}
<p>Your cart is empty</p>
{% endif %}
Output (if username is empty):
Hello, Guest!
Your cart is empty
💡 Important Tips:
-
Always close if statements with
{% endif %} -
Use
eliffor multiple conditions, not multipleifstatements -
Operators:
==,!=,<,>,<=,>= -
Logical operators:
and,or,not - Empty lists, None, False, 0, and "" are considered false