Open In App

What is the equivalent of None in django Templates

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, `None` is a special value that means "no value." When using Django templates, you might need to check if a variable is `None` to show something else or handle errors. In the Django template, the equivalent to the `None` keyword is the `None` itself. Now, let us change some content in the template when a specific variable is None.

Syntax to use None in Django Templates using {% if %} Template Tag

The {% if %} template tag is used to evaluate a condition and display content if the condition is true. To check if a variable is equivalent to None, we can use the {% if %} tag with the is None syntax.

Here's an example:

HTML
{% if my_variable is None %}
    <!-- display default value or handle error -->
{% endif %}

In this example, my_variable is the variable we want to check. If it's equivalent to None, the code inside the {% if %} block will be executed.

Code Example

Create a new Django project and app:

 django-admin startproject myproject
cd myproject
python manage.py startapp myapp

In myapp/views.py, add the following code:

Python
from django.shortcuts import render

def my_view(request):
    my_variable = None
    return render(request, 'my_template.html', {'my_variable': my_variable})


In myapp/templates/my_template.html, add the following code:

HTML
<!-- my_template.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Django Template Example</title>
</head>
<body>
    <h1>Django Template Example</h1>
{% if my_variable is None %}
    <p>my_variable is None</p>
{% else %}
    <p>my_variable is not None: {{ my_variable }}</p>
{% endif %}
    
</body>
</html>

Run the development server and access http://localhost:8000/ in your browser.

OUTPUT:

Capture

Now, let's modify the my_view function to set my_variable to a non-None value:

Python
def my_view(request):
    my_variable = 'Hello, World!'
    return render(request, 'my_template.html', {'my_variable': my_variable})

Output:

Run the development server again and access http://localhost:8000/ in your browser.

Capture


In Django templates, we use `is None` within the `{% if %}` tag to check if something is `None`. This lets us show default values or handle errors.


Practice Tags :

Similar Reads