Compare two integers in Python Django

In this Python Django tutorial, I will show you How to compare two integers in Python Django.

First, you will understand about different operators that you can use to compare the integers in Python Django. After that, I will explain to you how to compare two integers in the Django view function.

Finally, you will also understand how to compare two integers in the Django template, here you will pass the two integers from the Django view to the template and then compare the two values in your template.

Comparison Operators in Python

In this section, you will learn about what a comparison operator is and the different kinds of comparison operators available in Python.

In Python, a comparison operator is also known as a relational operator. Comparison operators are used to compare the values of two operands and return True or False depending on whether the condition is satisfied or not.

The comparison operators available in Python are listed below.

OperatorOperator NameDescription
==EqualityThe condition becomes true if the values of two operands are equal.
!=InequalityWhen the values of two operands differ, the condition is true.
>Greater thanIf the left operand’s value is greater than the right operand’s value, the condition is true.
>=Greater than or Equal toThe condition is true if the value of the left operand is larger than or equal to the value of the right operand.
<Less thanIf the left operand’s value is less than the right operand’s value, the condition is true.
<=Less than or Equal toThe condition is true if the value of the left operand is less than or equal to the value of the right operand.
Operators

Read: If statement in Django template

Now you know about the different comparison operators from the above table, let’s know where you can use these operators in Django to compare the integers.

How to compare two integers in Python Django

In Django, you can compare two integer values at two places, in Django views and templates.

  • Using Views: Views are Python functions or classes that receive and respond to web requests in the Django framework. A plain HTTP response, an HTML template response, or an HTTP redirect response that sends the user to another page can all be used as responses.
  • Using Template: Django templates use tags and filters to define a language that’s similar to Python—but isn’t Python. Tags are similar to the keywords and functions in the template language.
    • Keywords and functions in Python offer control flow and the tools on which your code is constructed. Inheritance, conditional operation, looping, comments, and text handling are all provided by Django’s built-in tags.
READ:  Python Django MySQL CRUD

Compare two integers in view

In this section, you will learn how to use Django’s view to compare two integers. Let’s, clarify our concepts by using various examples.

I’ll show you the project’s urls.py and the app’s urls.py file before I start the demonstration. As it remains the same in all of the examples. You get or create these two files when creating a new Django project.

Suppose you have created a project named ‘django_output’ and in that project folder you find the file named ‘urls.py’ and this file generally you get it in any Django project by default.

And in that file add the following lines of code.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('python_html.urls'))
]
Compare Two Integers in View Project URL

This means that when you open your project in the browser, it will take you to your python_html.urls.

Now, open the Django app ‘python_html’ and create a file called urls.py in that file write the following lines of code.

from django.urls import path
from .views import *


urlpatterns = [
    path('', home, name='home')
]
Compare Two Integers in View App URL

In the above code, add URL path (”, home, name=’home’), whenever someone hits the URL ‘http://127.0.0.1:8000/’, the view named home is called.

Open the views.py file of your Django app ‘python_html’ and add the following lines of code.

from django.http import HttpResponse

# Create your views here.

def home(request):
    x = 6
    y = 6
    if(x == y):
        html = "<html><body><b>Yes, X is equals to Y </b></body></html>"
        return HttpResponse(html)
    else:
        html = "<html><body><b>No, X is not equal to Y</b></body></html>"
        return HttpResponse(html)
Compare Two Integers in Home View

In the above code lines 17 and 18 define two integers, x & y, and then use the equality (x==y) operator at line 19 within the if statement to compare them.

At line 21 return the html page using the HttpResponse(html), if the condition (x==y) becomes true. The HTML page outputs the result ‘Yes, X is equal to Y’.

If the condition is false, then the the code within else part is executed. Which returns the HTML page containing the message ‘No, X is not equal to Y’.

READ:  Python function is not implemented for this dtype: [how->mean,dtype->object] error

Now, if run the development server and move to the mapped URL, you will get the following output.

compare two integers in view

The output shows that the value of variable X is equal to that of variable Y, which means variables X and Y contain the same value.

Take one more example, where you see how to use the inequality (!=) operator which is read as ‘is not equal to’.

So again modify the view function home and change the if(x==y) to if(x!=y), which means this checking if X is not equal to Y.

from django.shortcuts import render, get_object_or_404
from .models import Product

from django.http import HttpResponse

# Create your views here.

def home(request):
    x = 6
    y = 6
    if(x != y):
        html = "<html><body><b>Yes, X is equals to Y </b></body></html>"
        return HttpResponse(html)
    else:
        html = "<html><body><b>X is not equal to Y: True</b></body></html>"
        return HttpResponse(html)
Compare Two Integers in Python Django Inequality Operator

In the above code define two integers, x & y, and then use the inequality operator (X!=Y) to compare them. Then render the result on the HTML page.

Again open the URL ‘http://127.0.0.1:8000/’ and you will see the output as shown below.

how to compare two integers in python django

In the above, you can see that the message is ‘X is not equal to Y: True’ which means the value within variables X and Y is different.

You can use all the comparison operators that you have learned in the above table as instead of (X!=Y), you can check if one value is greater than another using (X>Y), it checks if the value within the variable X is greater than other values in the variable Y.

Read: Convert HTML page to PDF using Django in Python

Till now you know how to compare two integers within view, let’s see how to compare two integers in the Django template.

Compare two integers in the template

In this section, you will learn how to use Django’s template tag to compare two integers. Let’s, clarify our concepts by using various examples.

Syntax:

{% if variable boolean_operator value %}

        Statement To Print

{% endif %}

If you remember in the previous section you compare the two integers within view using the IF statement. In that case, you can also write the If conditional statement in your Django template.

This means Django allows you to write Python-like syntax in your HTML code. For writing the code like the If statement follow the above given syntax.

READ:  Matplotlib plot a line (Detailed Guide)

Open the views.py file of your Django app ‘python_html’ and modify the view function home by adding the following lines of code.

from django.shortcuts import render

# Create your views here.

def home(request):
    x = 100
    y = 150
    return render(request, 'home.html', {'x':x, 'y':y})
Compare Two Integers in Python Django Template

In the above lines 17 and 18 define the two variables x and y with values 100 and 150 respectively. Then pass these two variables as context to the template file home.html.

Create new folder templates and in that folder create a new fill called home.html, then add the following line 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>PythonGuides</title>
</head>
<body>
    <p>
        {% if x == y %}
        {{ x }} is equal to {{ y }}
        {% else %}
        {{ x }} is not equal to {{ y }}
        {% endif%}
    </p>
</body>
</html>
Compare Two Integers in Python Django Template Data

The above code accepts the data through context and uses the Django template tag to compare the values within variables x and y.

  • For example, in line 11, the code {% if x == y %} checks if the x is equal to y using the equality (==) operator. If both variable values are equal then it outputs the message x is equal to y using the code { x }} is equal to {{ y }}.
  • Otherwise, if the value within variables x and y is not equal then else part {% else %} is executed and shows the message x is not equal to y using the code {{ x }} is not equal to {{ y }}

If you again run the URL ‘http://127.0.0.1:8000/’, you see the output as shown below.

compare two integer in template

Let’s take one more example where you see how to use the less than (<) operator. For that open the home.html file and change the conditional template tag as shown below.

The home.html file:

<!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>PythonGuides</title>
</head>
<body>
    <p>
        {% if x < y %}
        {{ x }} is less than {{ y }}
        {% else %}
        {{ x }} is greater than {{ y }}
        {% endif%}
    </p>
</body>
</html>
Compare Two Integers in Python Django Template Less Than Operator

Here, we add less than the boolean operator in the template using {%if%} and {%else%} tag. If the tag evaluates the variables, If the condition is “true” the contents of the block are output, otherwise, else tag contents block is output.

compare two integer in template tag

In the output, you can see the message ‘-10 is less than 10’ which means the code within the IF part is true.

So you can use the different comparison operators with conditional template tags to compare two integers in Django.

In this Django tutorial, you learned how to compare two integers in Python Django. Also, learned about different comparison operators that you can use to compare two integers in Django. Additionally, you learned two ways to compare two integers in Django.

Also, take a look at some more Django tutorials.