If Condition In Django Template

In this Django tutorial, I will explain the use of the if condition in Django template. I will show some 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. To render the dynamic data in Django, you can use 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 in a dynamic way.

Also, you will learn about nested IF condition in Django template.

If Condition in Django Template

If you are already familiar with other programming languages such as C, C++, Java etc. Then, you know how to handle the flow of the program where you need to execute or run the specific part code based on the conditions.

For that, you use the IF statement to handle the code, which is based on the decision. You can also use the IF condition at your template or front end in your Django.

For that, you need to use the following syntax to execute the block of code based on the IF conditions.

{% if <condition> %}
  <statement to be executed if the condition returns true>
{%else%}
<statement to be executed if the condition returns false>
{% endif %}

Now look at the above syntax, that’s very easy to use. So Django provides the concept of template tags that allow you to write Python-like syntax at your front-end side or in your Django template.

In Django, the IF template tag is one of the tags that allows you to execute specific parts of code based on the provided conditions.

You can consider from the syntax within {% If <condtion>%}, you can write pure python IF statement to check the conditions, and if the condition, is true, then the code after the IF is executed.

Otherwise, if the condition is false, then code after the {%else%} part is executed. Finally, the tag {%endif%} means the end of the IF tag.

Let’s see, for example, how to use the IF condition in the Django template. For example, at my side, I created a Django project named ‘django_iftag’ and, in that project, created a Django app called ‘django_ifapp.’

If Condition in Django Template Creating Project

After this properly configured your Django app or project so that it shouldn’t show any error while running the Django server. If you don’t know how to create or setup Django project, then follow the tutorial How to create Django project.

First, configure the URL pattern at the project level, so open the urls.py file of your Django project ‘django_iftag’.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('django_ifapp.urls'))
]
Project URL If Condition in Django Template

Now open the views.py file of your Django app ‘django_ifapp’ and add the following lines of code.

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, 'django_if.html', dict)
Index View If Condition in Django Template

Then also, configure the URL path at the Django app level, so create a new file urls.py in your Django app ‘django_iftag’, and in that file, add the following codes.

from django.urls import path
from .views import *

urlpatterns = [
    path('', index, name='index')
]

Now, after that, create a folder called templates in your Django app ‘django_ifapp’ and again create a new file called ‘django_if.html’ and add the following lines of code.

<!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>
If Condition in Django Template Creating Template

Now in the above code, look at the line from 17 to 19, the IF template tag is used, within If tag the condition is (number1 > number2). If the number1 is greater than number2 then it render the code part ‘<h4>{{number1}} is greater than {{number2}}</h4>’.

At line 19 the {%endif%} end of the IF condition in Django template.

Finally open your terminal and type the below command to run the Django server.

python manage.py runserver

You see the output as shown below.

If Condition in Django template User Input

Now enter the first and second numbers, and click on the check button.

If Condition in Django template

As you can see in the above output, 5 is greater than 4, let me explain what’s happening. When you enter the two values 5 and 4 in the input box and click on the check button.

The entered data is sent to the view ‘index’ if you remember. The view code is shown below.

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, 'django_if.html', dict)

The view takes the entered values by a user using the request.GET.get() method and stores in the variable number1 and number2.

Then both variables data are passed to the Django template named ‘djano_if.html’ as context. Then at your front-end side the IF tag {% if number1 > number2 %} checks if the number1 is greater than number2.

If the condition becomes true, it executes the code part <h4>{{number1}} is greater than {{number2}}</h4>, which shows the output as indicating the number1 is greater than number2.

You can think of {% if number1 > number2 %} as equal to {% if 5 > 4 %}. But what will happen if you pass the first number as a smaller value and the second number as a larger value?

Let’s see by entering the number.

User Input If Condition in Django Template

As soon as you click on the check button with the first number as a smaller number and the second as a larger number, it clears the input field.

Because the {% if number1 > number2 %} gets executed only if the number1 is greater than number2 and the above this part becomes false, this is the reason input field get cleared or re-rendered.

So how to handle the situation when if condition becomes false, in that case use the tag {%else%} and specify the code block that will be executed when the IF condition is false.

The next section is about ELSE tag that is used with IF condition in Django.

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 given below:

{% if <condition> %}
   <statements or HTML if the condition returned True>
{% else %}
   <statements or HTML if the condition returned False>
{% endif %}

Now update the template file ‘django_if.html’ with else tag as shown below.

{% if number1 > number2 %}
      <h4>{{number1}} is greater than {{number2}}</h4>
    {%else%}
    <h4>{{number1}} is smaller than {{number2}}</h4>
    {% endif %}
If Condition in Django Template Else Tag

In your template, add the bold part of the code that is shown above. Now, again, run the Django server and enter the first values as 4 and the second values as 5, then click on the check button.

Else Tag If Condition in Django Template

In the above picture, the output is 4 is smaller than 5 which means this time else part is executed. This is how to handle the flow of program using the IF-ELSE tag in Django template.

In the above example you have compared or check the condition of type integer, you can also compare the string using the IF condition in Django template.

If Condition in Django Template Using String

Suppose instead of number you are passing the string data to the template, how you can compare the string using IF tag in Django and execute particular code based on the string comparision.

For that, you can use the same IF condition that you have used for the number, so instead of number as a condition, specify the string that you want to compare.

The syntax is very simple.

{% if <condition_with_string> %}
   <statements or HTML if the condition returned True>
{% else %}
   <statements or HTML if the condition returned False>
{% endif %}

Open the views.py file and add the new view called validate.

def validate(request):
      username = request.GET['user']
      return render(request, 'validate.html', {'username' : username})
If Condition in Django Template Using String View Validate

In the above code at line 12, a new view is defined named ‘validate’, which accepts the request object as a parameter.

Then at line 13 extracting the data from the variable user that comes with request object using the request.GET() method and stored in the variable username.

After that passing the extracted user data to the template ‘validate.html’ as context.

Also, update the URL path for this new view.

from django.urls import path
from .views import *

urlpatterns = [
    path('', index, name='index'),
    path('validate', validate, name = 'validate')
]
If Condition in Django Template Using String URL Path

Create a new template file ‘validate.html’ and add the following lines of codes.

<!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>
Template Validate If Condition in Django Template Using String

In the above code at line 10 {% if username == “admin” %} checks if the username is equal to the string ‘admin’.

If the value within variable username is admin then IF part becomes true and the code <h3>The user is admin user</h3> is executed, otherwise else part of the code <h3>The user is not admin user</h3> is executed.

Also create a new template file called user_input.html and add the following lines of code.

Template User If Condition in Django Template Using String

Also, update the view index by adding the following code.

from django.shortcuts import render
def index(request):
      return render(request, 'user_input.html')

Then run the Django server again, and you will see the page as shown below.

If Condition in Django Template Using String User Page

In the input box add the string ‘admin’ and click on the Submit button. After clicking on the Submit button, you see the validate template showing message ‘The user is admin user’ as shown in the below output.

If Condition in Django Template Using String Comparison

You can see that the output is different this time. In this way, you can compare strings in a Django template using the if-else template tag.

If Not Condition in Django Template

Let’s see an example where you can use the not operator with the if-else template tag in Django. The If not condition in Django is opposite of the If condition in Django template.

You will use an if-else tag to determine if a variable contains any value or not and the output will be rendered accordingly.

Open the validate.html file and update the code using the below code.

<!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>

Run the Django server don’t enter any text into the input field and click on the Submit button. After clicking on the submit button it shows the output as ‘No username is given’.

If not condition in Django template

When the user submits the empty form without a username, the code ‘{% if not username %}’ checks if any user name exists in the variable username. In this case, you haven’t provided any user names to show the condition becomes true and the IF part of the code is executed.

Now, suppose you have provided the user name as ‘Helen’ into the input field, then the {% else %} part of the code is executed because this time the IF condition becomes false.

django template not operator

This is how you can use the operator not with IF condition in the Django template.

Nested If Else in Django Template

When you learn about the if-else statement in different programming languages, you often learn the nested if-else structure also. Similarly, in Django template language also, you 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 where you will create a sample example with nested if-else structure in a Django template for a grading system. In this example, you will see the different grades based on the provided marks of the students.

First of all, let’s create the template marks.html, where the user inputs the marks.

<!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>
Nested If Else in Django Template Marks

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.urls import path
from .views import *

urlpatterns = [
    path('', index, name='index'),
    path('validate', validate, name = 'validate'),
    path('result', results, name = 'results')
]
Nested If Else in Django Template View URL Path

Update the view named index and add new view called results with the following code.

def index(request):
    return render(request, 'marks.html')

def results(request):
    name = request.GET['name']
    marks = float(request.GET['marks'])
    data = {
            'name': name,
            'marks': marks
    }
    return render(request, 'validate.html', data)
Nested If Else in Django Template View

Finally, you 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. So update the validate.html template by adding the following lines of code.

<!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>
Nested If Else in Django Template Validate

In the above code from lines 10 to 22, nested IF-ELSE tag is specified to show the grade based on the provided marks. Here the tag {%elif <condition> %} is used to specify more than one condition.

After this, run the Django server once more, and you see the page as shown below.

Student Page Nested If Else in Django Template

Then enter the student name as Roman and marks as 80, after that click on the submit button.

Student Grade Nested If Else in Django Template

After clicking on the submit button it shows the grade for the student marks as ‘Roman got B grade’.

This is how to use the Nested If Else in Django Template to specify multiple conditions in a nested way.

Conclusion

In this Python Django tutorial, you learned the If condition tag in Django template to handle the decision based code. You also learned how to use the not operator with If condition in Django. Finally, you learned about nested if-else tags in the Django template.

You may also like to read the following tutorials on Django.