Create a Calculator app in Python Django

In this Python Django tutorial, we are going to discuss how to create a Calculator app in the Django framework. We will create this app using HTML templates and we will also use Bootstrap and CSS to make our application look dynamic.

In this Django Calculator application, we will display a numeric calculator with buttons displaying mathematical operations such as add, subtract, multiply, and delete. A reference picture is shown below of how our app will look after completion.

Calculator in Python Django
Django Calculator application

How to create a Calculator app in Python Django

To create a Calculator application in Python Django we need the basic configurations to set up our project and some prerequisites which are required to create an application. Below are the steps we will follow to create a Calculator app in Python Django.

Step 1: Setup a Python Django Project

To set up a Django project create a folder (in case not created) in which you want to set up your project open that folder in vs code and run the below command in the terminal to create a virtual environment.

python -m venv venv

now we have created our virtual environment and to activate this virtual environment run the below command.

venv\Scripts\activate

Create a Django Project and application

Create a Django project using the below command in the VS code terminal or the command prompt(run as administrator). After running this command you will get the default directories of a Django project.

django-admin startproject djangocalculator

We need to move inside the project directory to access the manage.py file to work within our Python Django project directory. Follow the below command in the terminal.

cd djangocalculator

After entering the Django directory we need to create an application named calculator, For that run the below command.

python manage.py createapp calculator

Step 2: Creating templates

In this step, we are going to create a template to design the structure of our Django calculator using Html and bootstrap. First, create a folder named templates in the base directory and then create an HTML file named calc.html after that follow the below code in that HTML file.

<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Calculator</title>
    <link rel="stylesheet" href="{% static '/css/calc.css' %}">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  </head>
  <body>
    <section id="first">
      <div class="container-fluid">
        <div class="col-sm-12 header">
          Calculator
        </div>
      </div>
    </section>
    <section id="second">
      <form class="" action="calculation" method="post">
        {% csrf_token %}
      <div class="container-fluid">
        <div class="row">
          <div class="col-sm-2 left">
            <!-- left -->
          </div>
          <div class="col-sm-8 middle">
            <!-- main -->
            <div class="result">
              <span id="ques">{{values}}</span>
              <input type="text" name="values" id= "result" placeholder="0" value={{result}} >
            </div>
            <div class="keypad">
              <div class="row">
                <div class="col-sm-1">

                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block spc_btn" id="left_small" onclick="insertTextInInputValue('(');">(</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block spc_btn" onclick="insertTextInInputValue(')');">)</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block spc_btn" onclick="insertTextInInputValue('%');">%</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block spc_btn" onclick="insertTextInInputValue('AC');">AC</button>
                </div>
                <div class="col-sm-1">

                </div>
              </div>
              <div class="row">
                <div class="col-sm-1">

                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block num_btn" onclick="insertTextInInputValue(7);">7</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block num_btn" onclick="insertTextInInputValue(8);">8</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block num_btn" onclick="insertTextInInputValue(9);">9</button>
                </div>
                <div class="col-sm-2">
                   <button type="button" class="btn btn-block spc_btn" onclick="insertTextInInputValue('&divide');">&#247;</button>
                </div>
                <div class="col-sm-1">

                </div>
              </div>
              <div class="row">
                <div class="col-sm-1">

                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block num_btn" onclick="insertTextInInputValue(4);">4</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block num_btn" onclick="insertTextInInputValue(5);">5</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block num_btn" onclick="insertTextInInputValue(6);">6</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block spc_btn" onclick="insertTextInInputValue('x');">&#215;</button>
                </div>
                <div class="col-sm-1">

                </div>
              </div>
              <div class="row">
                <div class="col-sm-1">

                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block num_btn" onclick="insertTextInInputValue(1);">1</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block num_btn" onclick="insertTextInInputValue(2);">2</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block num_btn" onclick="insertTextInInputValue(3);">3</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block spc_btn" onclick="insertTextInInputValue('-');">-</button>
                </div>
                <div class="col-sm-1">

                </div>
              </div>
              <div class="row">
                <div class="col-sm-1">

                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block num_btn" onclick="insertTextInInputValue(0);">0</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block spc_btn" onclick="insertTextInInputValue('.');">.</button>
                </div>
                <div class="col-sm-2">
                  <button type="submit" class="btn btn-block btn-primary equal_btn">=</button>
                </div>
                <div class="col-sm-2">
                  <button type="button" class="btn btn-block spc_btn" onclick="insertTextInInputValue('+');">+</button>
                </div>
                <div class="col-sm-1">

                </div>
              </div>
            </div>
          </div>
          <div class="col-sm-2 right">
            <!-- right -->
          </div>
        </div>
      </div>
      </form>
    </section>

  </body>
  <script type="text/javascript">
  // var theTotal = 0;
  // $('#1').click(function(){
  // $('#result').val(1);
  // });
  function insertTextInInputValue(buttonValueIs){
            if (buttonValueIs == "AC")
            {
              $('#ques').text('Ans : 0');
              $('#result').val(0);
            }
            else {
              var inputElementIs = document.getElementById("result");
              inputElementIs.value =  inputElementIs.value + buttonValueIs;
              $('#result').val(inputElementIs.value);
            }
        }

// $('#tussenstand').val("Total: "+theTotal);
  </script>
</html>

Create a CSS static file

READ:  JWT Authentication Using Django Rest Framework

In this step, we are going to create CSS for our app to make it looks more dynamic. First, create a folder named static, and again create a folder name CSS and then create a file name calc.css

djangocalculator>static>CSS

.header{
  background-color: #329A97;
  text-align: center;
  font-size:50px;
  font-family: "calibri";
  color:#F4FA3C;
  letter-spacing: 7px;
  text-decoration: underline;
}
#second{
  margin-top: 20px;
}

/* #second .left,.right{
  border:2px solid yellow;
} */
#second .middle{
  border:2px solid lightgrey;
  border-radius: 5px;
}

#second .middle .result{
  /* border:2px solid red; */
  height: 60px;
  width: 80%;
  margin: 5% 10%;
  /* border-radius: 10px; */
}
#second .middle .result input{
  width: 100%;
  height:100%;
  font-size: 30px;
  font-family: "calibri";
  border-radius: 10px;
  text-align: right;
  padding-right: 12px;
}
#second .middle .result input:focus {
  border-radius: 10px;
}
#second .middle .keypad{
  margin: 20px 15%;
  /* margin-left: 30%; */
  margin-bottom: 5%;
  /* margin-left: 10%; */
}
#ques{
  /* font-weight: 100; */
  /* text-align: right; */
  float:right;
}
#second .middle  .keypad  .spc_btn{
  /* border: 2px solid black; */
  margin: 5px 5px;
  background-color: #dfe1e5;
  /* max-width: 70%; */
  font-weight:bold;
}

#second .middle  .keypad  .num_btn{
  margin: 5px 10px;
  background-color:#f1f3f4;
  border-radius: 4px;
  text-align: center;
  padding-top: 8px;
}

#second .middle  .keypad  .equal_btn{
  margin: 5px 10px;
  /* background-color:#4285f4; */
  border-radius: 4px;
  /* background-color:#e8eaeb; */
  /* color:white; */
  font-weight:bold;
  /* text-align: center; */
  padding-top: 8px;
 }
#second .middle  .keypad  .spc_btn:hover{
  background-color:#d7d9dd;
}
#second .middle  .keypad  .num_btn:hover{
  background-color:#e8eaeb;
}


/* a{
  text-decoration: none;
} */

Step 3: Creating URLs in the project

from django.contrib import admin
from django.urls import path,include
# from calculator import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('calculator.urls'))
]

Step 4: Creating views in the application

In this step, we will create views to define the mathematical operation for our application using for loops. In the views, we will also import a re-function.

READ:  How to build a contact form in Django using bootstrap

re syntax stands for Regular Expression which specifies a set of strings that matches it. This module has functions that check a particular string matches a given regular expression or string that comes down to the same thing.

from django.shortcuts import render
from django.http import HttpResponse
import re
# Create your views here.
def greetings(request):
    # var=request.GET['var']
    res=render(request,'calc.html')
    return res

def calculation(request):
    if request.method=="POST":
        values=request.POST['values'] #string having whole ques
        print(values)
        vals=re.findall(r"(\d+)",values) #extrect values
        operators=['+','x','÷','-','.','%']
        opr=[]
        for v in values:
            for o in operators:
                if v==o:
                    opr.append(o)
        print(opr)                      #extract operators
        print(re.findall(r"(\d+)",values))

        for o in opr:
            if o=='.':
                i=opr.index(o)
                res=vals[i]+"."+vals[i+1]
                vals.remove(vals[i+1])
                opr.remove(opr[i])
                vals[i]=res
                print(vals)
                print(opr)
        for o in opr:
            if o=='%':
                i=opr.index(o)
                res=(float(vals[i])/100)*float(vals[i+1])
                vals.remove(vals[i+1])
                opr.remove(opr[i])
                vals[i]=res
                print(vals)
                print(opr)
        for o in opr:
            if o=='÷':
                i=opr.index(o)
                res=float(vals[i])/float(vals[i+1])
                vals.remove(vals[i+1])
                opr.remove(opr[i])
                vals[i]=str(res)
                print(vals)
                print(opr)
        for o in opr:
            if o=='x':
                i=opr.index(o)
                res=float(vals[i])*float(vals[i+1])
                vals.remove(vals[i+1])
                opr.remove(opr[i])
                vals[i]=str(res)
                print(vals)
                print(opr)
        for o in opr:
            if o=='+':
                i=opr.index(o)
                res=float(vals[i])+float(vals[i+1])
                vals.remove(vals[i+1])
                opr.remove(opr[i])
                vals[i]=str(res)
                print(vals)
                print(opr)
            if o=='-':
                i=opr.index(o)
                res=float(vals[i])-float(vals[i+1])
                vals.remove(vals[i+1])
                opr.remove(opr[i])
                vals[i]=str(res)
                print(vals)
                print(opr)

        
        # print(opr)
        if len(opr)!=0:
            if opr[0]=='÷':
                result = float(vals[0])/float(vals[1])
            elif opr[0]=='x':
                result = float(vals[0])*float(vals[1])
            elif opr[0]=='+':
                result = float(vals[0])+float(vals[1])
            else :
                result = float(vals[0])-float(vals[1])
        else:
            result = float(vals[0])

        final_result=round(result,2)
        print(final_result)
       


    res=render(request,'calc.html',{'result':final_result,'values':values})
    return res

Step 5: Creating URLs in the application

from django.urls import path
# from django.contrib import admin
from . import views

urlpatterns = [
    
    path('', views.greetings),
    path('calculation',views.calculation)
]

Step 6: Run the server to view our application

We are done with all the necessary configurations of our application and now we are ready to run our app on the server where we can view the app. To run the development server we will use the runserver command.

>  python manage.py runserver

Now the URL link  http://127.0.0.1:8000/ page will redirect you to the server where we will see our application.

READ:  Payment Gateway Integration with Django
Python Django Calculator app
Calculator app in Django

Conclusion

In this Python Django tutorial, we learned how to create a Calculator application in Python Django framework. We have also learned how to create for loops to render mathematical operations in our calculator.

We also got a good understanding of re syntax and its functionalities with which we have imported maths functions in our calculator application.

You may like the following Django tutorials: