In this Django tutorial, I will explain the use of the if-else statement in a Django template. I will show some of the examples of the use cases of an if-else statement in a Django template.
HTML pages are static in nature. However, Django templates can make a page dynamic using various techniques. For example, using the template tags.
The if template tag is one of the template tags in Django that can be used to render HTML content for a particular condition. Let us see how to use the if template tag in Django.
- How to use if statement in Django template
- If tag in Django template example
- If else tag in Django template
- If else tag in Django template example
- Django template if equal string
- If not condition in Django template
- Nested if else in Django template
- Multiple if condition in Django template
- For loop with if condition in Django template
How to use if statement in Django template
In a Django template, the if statement is referred to as if tag. You can use this if tag to render HTML content based on a particular condition. The syntax of the if template tag is:
{% if <condition> %}
<statement to be executed if the condition returns true>
{% endif %}
In a Django template, you have to close the if template tag. You can write the condition in an if template tag. Inside the block, you can write the statements or the HTML code that you want to render if the condition returns a True value.
Let us understand this with the help of an example.
If tag in Django template example
Now let us see an example of the if tag. I have created an example where I will enter two numbers and compare them inside a Django template.
The following is the Django template where I will submit the two numbers:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
</head>
<body>
<form action="" method="get">
<h3> Enter First number: </h3><br>
<input type="text" name="number1" placeholder="Enter First number"><br>
<h3> Enter Second number: </h3><br>
<input type="text" name="number2" placeholder="Enter Second number">
<input type="submit" value="Check">
</form>
{% if number1 > number2 %}
<h4>{{number1}} is greater than {{number2}}</h4>
{% endif %}
</body>
</html>
Also, I am showing the result in the same template. You can see my urls.py file:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name = 'index'),
]
Now, in the views.py file, I will receive the parameters and render them in the same template. This is my views.py file:
# importing the necessary libraries
from django.shortcuts import render
def index(request):
number1 = int(request.GET.get('number1', 0))
number2 = int(request.GET.get('number2', 0))
dict={
'number1' : number1,
'number2' : number2
}
return render(request, 'index.html', dict)
Now let us see the output.
You can see the output when the first number is greater than the second number. In this way, you can use the if tag in a Django template.
Also, read: Python Django vs Flask
If else tag in Django template
Similarly, you can also use else along with the if tag. The syntax for the if-else template tag is:
{% if <condition> %}
<statements or HTML if the condition returned True>
{% else %}
<statements or HTML if the condition returned False>
{% endif %}
Let us see an example of the if-else template tag.
If else tag in Django template example
In this example, I will submit a number and it will be compared in the Django template whether the number is even or odd. Below is my Django template where I will take a number and check the number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
</head>
<body>
<form action="" method="get">
<h3> Enter a number: </h3><br>
<input type="text" name="number" placeholder="Enter a number">
<input type="submit" value="Check">
</form>
{% if number|divisibleby:"2" %}
<h4>The number is even</h4>
{% else %}
<h4>The number is odd</h4>
{% endif %}
</body>
</html>
But before that, let me show you the views.py file.
# importing the necessary libraries
from django.shortcuts import render
def index(request):
number = int(request.GET.get('number', 0))
return render(request, 'index.html', {'number': number})
In the URLs file, I have defined this page to redirect to itself only.
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name = 'index'),
]
Let us see the output now.
Now let us enter a number and check the output by clicking on the Check button.
You can see the number in the URL. The number is odd and we got the output accordingly.
In this way, you can use the if-else tag in a Django template.
Read: Python Django get admin password
Django template if equal string
In this section, I will demonstrate an example where I will compare a string in a Django template using an if-else template tag.
You can also use the ifequal template tag but it is deprecated after version 3.1. Therefore it is not recommended to use it. I will demonstrate how you can use the if-else tag instead of the ifequal tag.
In this example, I will be using two Django templates i.e one for submitting a string input and the other for rendering the result. The first template is index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
</head>
<body>
<form action="validate" method="get">
<h3> Enter the username: </h3><br>
<input type="text" name="user" placeholder="Enter the username"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
When the form is submitted, the user will be redirected to another URL endpoint. This URL endpoint is defined in the urls.py file as:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name = 'index'),
path('validate', views.validate, name = 'validate')
]
In the views.py file, I have defined a function named validate() that will collect the data from the form and render it inside a Django template. The views.py file is:
# importing the necessary libraries
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def validate(request):
username = request.GET['user']
return render(request, 'validate.html', {'username' : username})
Finally, I will use the if-else template tag in the Django template named validate.html. The user input entered in the form will be compared with a string i.e. “admin” and the result will be displayed accordingly. The Django template is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Show Username</title>
</head>
<body>
{% if username == "admin" %}
<h3>The user is admin user</h3>
{% else %}
<h3>The user is not admin user</h3>
{% endif %}
</body>
</html>
Now let us start the Django server and see the output.
The first time I will enter a random string. Let us see the output.
Now let us enter the string “admin” in the form input and see the output.
You can see that the output is different. In this way, you can compare strings in a Django template using the if-else template tag.
Note: In template language, use double quotes to handle the strings.
Read: Difference between app and project in Django
If not condition in Django template
Let us see an example where we can use the not operator with the if-else template tag in Django.
I will use an if-else tag to determine if a variable contains any value or not and the output will be rendered accordingly.
I am using the same setup that I defined in the above section i.e. all the files including views.py, urls.py, index.html will be the same in this example also. This time I will just change the Django template where I will use the if-else tag i.e. validate.html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Show Username</title>
</head>
<body>
{% if not username %}
<h3>No username is given</h3>
{% else %}
<h3>Username is: {{username}}</h3>
{% endif %}
</body>
</html>
Let us see the output now. Firstly, I will enter no username.
I will go to the previous page again and this time will submit a test username.
You can see when there was a value in the variable, I got the value as specified in the if-else template tag in the Django template.
In this way, you can use the not operator with an if-else template tag in Django.
Read: How to Create model in Django
Nested if else in Django template
When we learn about the if-else statement in different programming languages, we often learn the nested if-else structure also. Similarly, in Django template language also, we can use the nested if-else structure.
In a Django template, you can create a nested if-else structure like:
{% if marks <condition 1> %}
<statements or HTML to be rendered>
{% elif <condition 2> %}
<statements or HTML to be rendered>
{% elif <condition N> %}
<statements or HTML to be rendered>
{% else %}
<statements or HTML to be rendered>
{% endif %}
Now let us see an example. I will create a sample example where I will create a nested if-else structure in a Django template. I will create a simple example of a grading system, where the output will be rendered according to the given user input i.e. marks.
First of all, let us design the template where we will submit the user input, say index.html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grades</title>
</head>
<body>
<form action="result" method="get">
<h3> Enter Student Name: </h3><br>
<input type="text" name="name" placeholder="Enter Student Name"><br>
<h3> Enter Marks: </h3><br>
<input type="text" name="marks" placeholder="Enter Marks"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
After clicking the submit button, the form will redirect the user to a URL endpoint named result. Let us define this URL mapping in the urls.py file:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name = 'index'),
path('result', views.results, name = 'results')
]
Now let us define the function that will handle the request and pass the parameters to the next Django template in the views.py file:
# importing the necessary libraries
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def results(request):
name = request.GET['name']
marks = float(request.GET['marks'])
data = {
'name': name,
'marks': marks
}
return render(request, 'validate.html', data)
Finally, we will render this data inside a Django template named validate.html where we will use the if-else template tag for comparing the data and showing the result.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Show Username</title>
</head>
<body>
{% if marks >= 90 %}
<h3>{{name}} got A grade</h3>
{% elif marks >= 75 %}
<h3>{{name}} got B grade</h3>
{% elif marks >= 60 %}
<h3>{{name}} got C grade</h3>
{% elif marks >= 45 %}
<h3>{{name}} got D grade</h3>
{% elif marks >= 35 %}
<h3>{{name}} got E grade</h3>
{% else %}
<h3>{{name}} got F grade</h3>
{% endif %}
</body>
</html>
Let us see the output now by starting the server and visiting the index webpage.
Let us enter some data in the form and click on the Submit button.
You can see that we got the grade as specified in the if-else template tag.
In this way, you can use the nested if-else structure in a Django template.
Read: How to Get Current time in Django
For loop with if condition in Django template
While developing a Django application, you may need to render a list of items in a Django template. In that case, you generally use a for loop.
However, it is a good practice to validate if the list of items is empty or not. The looping statement should only execute if the list contains some items.
In that case, you can use an if-else template tag to verify if the list contains some items or not. In this section, I will demonstrate this with the help of an example.
I have created a sample employees’ database. I will render the names of the employees of a particular department in a Django template.
- Firstly, I will create a Django template where I will take a user input i.e. specify the department, say the name index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grades</title>
</head>
<body>
<form action="department" method="get">
<h3> Enter Department Name: </h3><br>
<input type="text" name="department" placeholder="Enter Department Name"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
- This form will redirect us to another URL enpoint named department. Let us map this URL enpoint with a function in our urls.py file:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name = 'index'),
path('department', views.department, name = 'department')
]
- Now we will create a function in our views.py file that will handle our request. We will retrieve the data of the employees from the database having a particular department specified by the user. The views.py file is:
# importing the necessary libraries
from django.shortcuts import render
from .models import Employees
def index(request):
return render(request, 'index.html')
def department(request):
dep = request.GET['department']
obj = Employees.objects.all().filter(department = dep)
data= {
'obj' : obj,
'dep' : dep
}
return render(request, 'department.html',data)
- Let me also show you the models.py file so that you can see how I have created the database:
from django.db import models
class Employees(models.Model):
emp_id = models.AutoField
name = models.CharField(max_length= 40)
department = models.CharField(max_length= 40)
salary = models.FloatField()
The above model class will create a table named Employees in the database.
- I have populated this table in the database using SQLite studio as I am using the default SQLite database. The data in the database is as follows:
- Now let us see how we can render the data fetched by our views.py file in a Django template named department.html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>List Employees by department</title>
</head>
<body>
{% if obj %}
<h3>List of Employees in {{dep}} department</h3>
<ol>
{% for emp in obj %}
<li>{{emp.name}}</li>
{% endfor %}
</ol>
{% else %}
<h3>Not a valid department</h3>
{% endif %}
</body>
</html>
- In the above template, I have used the if-else template tag to check if the variable named obj contain some data or not.
- If it contains some data, the employees’ names from the data will be rendered as an ordered list in the template. Otherwise, a different message will be rendered.
- Let us see the output now. I will start the Django server and visit the homepage of my Djnago application.
- Firstly, I will sumit a valid employee department.
- You can see that we got the names of the employees belonging to the department that we specified.
- Now let us repeat this step again, but this time I will enter any invalid string i.e. not a valid deparrtment.
You can see, we got the message that we defined in the else block of the if-else template tag.
You may also like to read the following tutorials on Django.
In this way, you can use the if-else tag before a for loop to put a validation check on a variable.
- How to use if statement in Django template
- If tag in Django template example
- If else tag in Django template
- If else tag in Django template example
- Django template if equal string
- If not condition in Django template
- Nested if else in Django template
- For loop with if condition in Django template
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.