Django If Template Tag

When working with Django, you may come across controlling the presentation of your data in templates. I’ve come to appreciate how Django’s template language simplifies this process. One of the most common tasks is using the if condition to display content based on certain criteria.

In this article, I’ll share my firsthand experience and walk you through how to use the if condition in Django templates. Whether you’re building a simple blog or a complex web application, understanding this will help you create dynamic and user-friendly pages.

Let’s get in.

What is the If Condition in Django Template?

The if condition in Django templates allows you to evaluate expressions and control what gets rendered on the page. It’s similar to the if statement in Python but adapted for templates, enabling you to show or hide HTML elements based on variables passed from your views.

This is particularly useful when you want to customize the user experience. For example, you might want to greet users differently based on their login status or display a special message during holidays like the Fourth of July.

Check out Python Django Form Validation

Basic Syntax of If Condition in Django Template

Here’s the simplest form of an if condition in Django templates:

{% if condition %}
    <!-- HTML to render if condition is true -->
{% endif %}

You can replace condition with any variable or expression you want to check.

Method 1: Simple If Condition

Let me show you a straightforward example. Suppose you have a view that passes a variable user_logged_in to your template:

# views.py
from django.shortcuts import render

def home(request):
    context = {
        'user_logged_in': True,
    }
    return render(request, 'home.html', context)

In your template, you can check this variable to display a welcome message:

<!-- home.html -->
{% if user_logged_in %}
  <h1>Welcome back, valued user!</h1>
{% else %}
  <h1>Welcome! Please log in to access more features.</h1>
{% endif %}

If user_logged_in is True, the first message shows up; otherwise, the else block executes.

You can see the output in the screenshot below.

django template if

Read How to Encrypt and Decrypt Passwords in Django

Method 2: Use If with Comparison Operators

Sometimes, you want to compare values. For instance, say you want to display a special message if today is the Fourth of July.

First, pass the current date from your view:

# views.py
from django.shortcuts import render
from datetime import datetime

def home(request):
    context = {
        'current_month': datetime.now().month,
        'current_day': datetime.now().day,
    }
    return render(request, 'home.html', context)

Now, in your template, you can check if the date is July 4th:

<!-- home.html -->
{% if current_month == 7 and current_day == 4 %}
  <p>Happy Independence Day, USA!</p>
{% else %}
  <p>Have a great day!</p>
{% endif %}

This will only show the Independence Day greeting on July 4th.

You can see the output in the screenshot below.

django if template

Check out Python Django Concatenate String

Method 3: Nested If Conditions

You can also nest if conditions for more complex logic. For example, imagine you want to greet users differently based on their age group:

# views.py
def home(request):
    context = {
        'user_age': 25,
    }
    return render(request, 'home.html', context)

In the template:

<!-- home.html -->
{% if user_age < 18 %}
  <p>Welcome, young visitor!</p>
{% else %}
  {% if user_age < 65 %}
    <p>Welcome, adult user!</p>
  {% else %}
    <p>Welcome, respected senior!</p>
  {% endif %}
{% endif %}

This way, you can tailor the message precisely.

You can see the output in the screenshot below.

template if django

Read Run Python Script in Django

Method 4: Use If with Variables and Filters

Django templates support filters, which you can combine with if conditions. For example, if you want to check if a string variable is empty or not, you can do this:

# views.py
def home(request):
    context = {
        'user_name': '',
    }
    return render(request, 'home.html', context)

Template:

<!-- home.html -->
{% if user_name|length > 0 %}
  <p>Hello, {{ user_name }}!</p>
{% else %}
  <p>Hello, guest!</p>
{% endif %}

If user_name is empty, it will greet the visitor as a guest.

Check out How to Use Python Django pre_save

Method 5: If Condition with Logical Operators

You can use logical operators like and, or, and not inside your if statements. For example, let’s say you want to display a message only if a user is logged in and has admin privileges:

# views.py
def home(request):
    context = {
        'user_logged_in': True,
        'is_admin': False,
    }
    return render(request, 'home.html', context)

Template:

<!-- home.html -->
{% if user_logged_in and is_admin %}
  <p>Welcome, Admin! You have full access.</p>
{% elif user_logged_in and not is_admin %}
  <p>Welcome, User! Limited access granted.</p>
{% else %}
  <p>Please log in.</p>
{% endif %}

This example shows how you can combine conditions to control your content precisely.

Read Build a Django Contact Form with Email

Important Tips from My Experience

  • Always ensure the variables you use in your if conditions are passed from the view; otherwise, Django will treat them as False or empty.
  • Django templates don’t support complex Python expressions. Keep your logic simple or handle complex logic in your views.
  • Use {% elif %} to avoid multiple nested if-else blocks, which improves readability.
  • Remember that Django template if conditions are case-sensitive.

Using if conditions in Django templates has been a game-changer in my projects. It helps create personalized user experiences without complicating the backend code.

Try these methods in your next Django project, and you’ll see how flexible and straightforward template conditions can be.

If you want to explore further, Django’s official documentation provides excellent insights into template tags and filters.

I hope you found this guide on the if condition in Django templates helpful. Feel free to experiment with these examples and adapt them to your projects.

Other Django articles you may like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.