Open In App

Build Calculator App Using Django

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will guide you through the process of creating a calculator app using Django. Our goal is to develop a versatile application capable of performing fundamental mathematical operations such as addition, subtraction, multiplication, and more. By the end of this tutorial, you will have a functional calculator that goes beyond the basic arithmetic functions found in a typical calculator, providing a hands-on introduction to building web applications with Django.

Calculator App Using Django

To install Django follow these steps.

Starting the Project Folder

To start the project use this command

django-admin startproject core
cd core

To start the app use this command

python manage.py startapp home

Now add this app to the ‘settings.py’

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"home",
]

File Structure

core

Setting Necessary Files

views.py : The Django view function ‘calculator’ checks if the request is a POST method. If true, it retrieves the ‘result’ parameter, calculates the result, and renders ‘index.html’ with the result. Otherwise, it renders ‘index.html’ without any changes.

Python3




from django.shortcuts import render
from django.http import HttpResponse
 
def calculator(request):
    if request.method == 'POST':
        result = request.POST.get('result', '')
 
        return render(request, 'index.html', {'result': result})
 
    return render(request, 'index.html')


urls.py : Defines Django URL patterns, routing ‘admin/’ to the admin interface and ” to the ‘calculator’ function from the ‘home.views’ module.

Python3




from django.contrib import admin
from django.urls import path
from home.views import *
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', calculator, name='calculator'),
]


Creating GUI

index.html : This HTML document defines a simple calculator web page. It includes styles for a centered layout with a background color, a calculator container with specific styling, and JavaScript functions for handling user input. The calculator allows users to perform basic arithmetic operations, and the result is displayed in an input field within a form.

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>Simple Calculator</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f2f2f2;
            margin: 0;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }
 
        .calculator {
            background-color: #ffffff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 5px;
            padding: 20px;
            width: 300px;
            text-align: center;
        }
 
        h1 {
            color: #4CAF50;
            font-family: 'Times New Roman', Times, serif;
            margin-top: 0;
        }
 
        input, button {
            margin: 5px;
            padding: 10px;
            font-size: 16px;
        }
 
        input {
            width: 80%;
        }
 
        button {
            width: 19%;
             
             
        }
    </style>
</head>
<body>
    <div class="calculator">
        <h1>GeeksforGeeks Calculator</h1>
        <form method="post" action="{% url 'calculator' %}">
            {% csrf_token %}
            <input type="text" id="result" name="result" value="{{ result }}">
            <br>
            <button onclick="clearResult()">C</button>
            <button onclick="appendToResult('7')">7</button>
            <button onclick="appendToResult('8')">8</button>
            <button onclick="appendToResult('9')">9</button>
            <br>
            <button onclick="appendToResult('4')">4</button>
            <button onclick="appendToResult('5')">5</button>
            <button onclick="appendToResult('6')">6</button>
            <button onclick="appendToResult('*')">*</button>
            <br>
            <button onclick="appendToResult('1')">1</button>
            <button onclick="appendToResult('2')">2</button>
            <button onclick="appendToResult('3')">3</button>
            <button onclick="appendToResult('-')">-</button>
            <br>
            <button onclick="appendToResult('0')">0</button>
            <button onclick="appendToResult('.')">.</button>
            <button onclick="calculate()">=</button>
            <button onclick="appendToResult('+')">+</button>
            <button onclick="clearResult()">Clear</button>
            <button onclick="appendToResult('/')">/</button>
        </form>
    </div>
 
    <script>
        // Update JavaScript functions to handle form submission
        function appendToResult(value) {
            document.getElementById('result').value += value;
        }
 
        function clearResult() {
            document.getElementById('result').value = '';
        }
 
        function calculate() {
            try {
                document.getElementById('result').value = eval(document.getElementById('result').value);
            } catch (error) {
                document.getElementById('result').value = 'Error';
            }
        }
    </script>
</body>
</html>


Deployement of the Project

Run these commands to apply the migrations:

python3 manage.py makemigrations
python3 manage.py migrate

Run the server with the help of following command:

python3 manage.py runserver

Output :

calculator



Similar Reads

Build a Calculator with React, Tailwind, and Django
This article will guide you in creating a calculator using React and Tailwind with the Django Framework. We'll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the calculator. What is a Calculator?A calculator is a device or tool designed for performing mathematical calculations. It typ
6 min read
Build a URL Size Reduce App with Django
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In this article, we will learn to build a URL shortener using Django. A URL shortener is used to reduce the size of long URLs. Short URLs are better for sharing purposes. In this article, we will use Bitly API to shorten our URL. For this, we
5 min read
Tip Calculator Project Using Django
In this article, we will guide you through the process of creating a Tip Calculator Project using Django. This interactive project requires users to input the bill amount, the desired percentage for the tip, and the number of people splitting the bill. The application will then compute and display the Total Tip per person along with the Total Amoun
6 min read
Build a To-Do application Using Django, React and Tailwind
This article will guide you in creating a To-Do application using React and Tailwind with the Django Framework. We’ll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the To-Do application. What is a To-Do application?A To-Do application, also known as a task management or productivity
6 min read
Build a Contact form Using Django, React and tailwind
This article will guide you in creating a Contact form Using Django, React, and tailwind. We’ll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Contact form. Build a Contact form Using Django, React and TailwindHere, is the step-by-step implementation of contact form using React, T
5 min read
Build a Clock Application using Django and React
The clock project aims to develop a simple yet functional clock application using modern web technologies. It combines the frontend capabilities of React.js for creating dynamic user interfaces with the styling power of Tailwind CSS for a sleek and responsive design. Additionally, the backend is built using Django, providing a robust framework for
4 min read
Build an Authentication System Using Django, React and Tailwind
In this article, we will guide you in building an Authentication system using React and Tailwind with the Django Framework that includes features like sign up, log in, forgot password, and reset password. We’ll explore the integration of Django, React, and Tailwind CSS and go through the step-by-step process of implementing the Authentication syste
17 min read
Adding Tags Using Django-Taggit in Django Project
Django-Taggit is a Django application which is used to add tags to blogs, articles etc. It makes very easy for us to make adding the tags functionality to our django project.Setting up Django Project Installing django-taggit pip install django-taggitADD it to Main Project's settings.py file C/C++ Code INSTALLED_APPS = [ 'django.contrib.admin', 'dja
2 min read
How to customize Django forms using Django Widget Tweaks ?
Django forms are a great feature to create usable forms with just few lines of code. But Django doesn't easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id
3 min read
Integrating Django with Reactjs using Django REST Framework
In this article, we will learn the process of communicating between the Django Backend and React js frontend using the Django REST Framework. For the sake of a better understanding of the concept, we will be building a Simple Task Manager and go through the primary concepts for this type of integration between React js and Django. Reactjs in a nuts
18 min read
Article Tags :
Practice Tags :