If Statement in Templates

A snippet showing how to use {% if %} and {% else %} in templates.


# models.py

from django.db import models

class Notice(models.Model):
    message = models.CharField(max_length=200)
    level = models.CharField(max_length=20, default="info")  # info, warning, error
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.message
      

# admin.py

from django.contrib import admin
from .models import Notice

@admin.register(Notice)
class NoticeAdmin(admin.ModelAdmin):
    list_display = ("message", "level", "is_active")
      

# Result (Conditional rendering)
# templates/alerts.html
{% if notice.is_active %}
  {% if notice.level == "warning" %}
    <div class="alert alert-warning">{{ notice.message }}</div>
  {% elif notice.level == "error" %}
    <div class="alert alert-danger">{{ notice.message }}</div>
  {% else %}
    <div class="alert alert-info">{{ notice.message }}</div>
  {% endif %}
{% else %}
  <div class="text-muted">No active notice.</div>
{% endif %}
      
Explanation:
  • Wrap content with {% if %} / {% elif %} / {% else %} for conditional blocks.
  • Truthy rules follow Python semantics; empty strings/lists are falsey.
  • Keep template logic simple-push complex decisions to the view/context.
  • Category Templates
  • Total Views 1298
  • Last Modified 20 January, 2026
  • Tags #templates #if #conditionals #logic
Previous snippet
For Loop in Templates
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.