Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Python | Loan calculator using Tkinter
Next article icon

Tip Calculator Project Using Django

Last Updated : 09 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Amount per person. This project is not only interesting but also straightforward, making it an excellent way to delve into Django development.

Tip Calculator Project Using Django

Below is the Implementation of the Tip Calculator Project 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:

jj

Setting Necessary Files

models.py : This Django model named `TipCalculation` has fields for bill amount, tip percentage, and number of people. It also includes optional fields for tip amount and total amount per person, allowing flexibility in data entry with blank and null values.

Python3
from django.db import models  class TipCalculation(models.Model):     bill_amount = models.DecimalField(max_digits=10, decimal_places=2)     tip_percentage = models.DecimalField(max_digits=5, decimal_places=2)     num_people = models.IntegerField()     tip_amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)     total_amount_per_person = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) 

views.py : This Django code defines a tip calculator view (`tip_calculator`) that processes form input, calculates tip details, and saves them to the database. The result view (`tip_calculator_result`) fetches the latest calculation from the database and displays it using templates. The calculation logic involves a `TipCalculatorForm` and the `TipCalculation` model, with a redirect to the result page upon successful form submission.

Python3
from django.shortcuts import render, redirect from .forms import TipCalculatorForm from .models import TipCalculation from decimal import Decimal  def tip_calculator(request):     if request.method == 'POST':         form = TipCalculatorForm(request.POST)         if form.is_valid():             instance = form.save(commit=False)                          # Get the selected tip percentage as a Decimal             tip_percentage = Decimal(request.POST.get('tip_percentage'))                          instance.tip_percentage = tip_percentage             instance.tip_amount = instance.bill_amount * (tip_percentage / Decimal(100))             instance.total_amount_per_person = (instance.bill_amount + instance.tip_amount) / instance.num_people             instance.save()             return redirect('tip_calculator_result')     else:         form = TipCalculatorForm()      return render(request, 'index.html', {'form': form})  def tip_calculator_result(request):     calculations = TipCalculation.objects.last()     return render(request, 'result.html', {'calculations': calculations}) 

forms.py : This Django form (`TipCalculatorForm`) is designed for the `TipCalculation` model, with fields for bill amount and number of people. It includes a radio button selection for tip percentages (5%, 10%, 15%, 25%). The form is tailored to capture input for tip calculations in the associated model.

Python3
from django import forms from .models import TipCalculation  class TipCalculatorForm(forms.ModelForm):     class Meta:         model = TipCalculation         fields = ['bill_amount', 'num_people']      tip_percentage = forms.ChoiceField(choices=[(5, '5%'), (10, '10%'), (15, '15%'), (25, '25%')], widget=forms.RadioSelect) 

project/urls.py : This Django configuration sets up URL patterns. The admin interface is accessible at `/admin/`, and the root URL (`/`) includes the URL patterns defined in the `home.urls` module, facilitating modular URL handling.

Python3
from django.contrib import admin from django.urls import path, include  urlpatterns = [     path('admin/', admin.site.urls),     path('', include('home.urls')), ] 

app/urls.py : This Django code sets up URL patterns for the 'tip_calculator/' and 'tip_calculator_result/' paths, linking them to the corresponding views. The names 'tip_calculator' and 'tip_calculator_result' can be used as references in the project.

Python3
from django.urls import path from .views import tip_calculator, tip_calculator_result  urlpatterns = [     path('tip_calculator/', tip_calculator, name='tip_calculator'),     path('tip_calculator_result/', tip_calculator_result, name='tip_calculator_result'), ] 

Creating GUI

index.html : This HTML code defines a simple web page for a Tip Calculator. It includes a form with fields for Bill Amount, Tip Percentage, and Number of People. The styling uses flexbox for layout, and the form submission is directed to the 'tip_calculator' URL. Tip Percentage options are presented as radio buttons. The styling emphasizes clarity and a clean design for user input.

HTML
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Tip Calculator</title>     <style>         body {             font-family: 'Arial', sans-serif;             background-color: #f4f4f4;             margin: 0;             padding: 0;             display: flex;             align-items: center;             justify-content: center;             height: 100vh;         }          h2 {             text-align: center;             color: #333;             margin-bottom: 20px;         }          form {             background-color: #fff;             border-radius: 10px;             padding: 20px;             box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);             display: flex;             flex-direction: column;             align-items: center;         }          label {             display: block;             font-weight: bold;             margin-bottom: 5px;         }          input, select {             width: 100%;             padding: 8px;             margin-bottom: 10px;             box-sizing: border-box;             border: 1px solid #ccc;             border-radius: 4px;         }          .tip-options {             display: flex;             margin-bottom: 10px;         }          .tip-option {             margin-right: 10px;         }          button {             background-color: #4caf50;             color: #fff;             padding: 10px;             border: none;             border-radius: 4px;             cursor: pointer;             width: 100%;         }          button:hover {             background-color: #45a049;         }     </style> </head> <body>     <form method="post" action="{% url 'tip_calculator' %}">         <h2>Tip Calculator</h2>         <br>         {% csrf_token %}         <label for="{{ form.bill_amount.id_for_label }}">Bill Amount</label>         {{ form.bill_amount }}         <br>         <label for="{{ form.tip_percentage.id_for_label }}">Tip Percentage</label>         <div class="tip-options">             {% for choice in form.tip_percentage %}                 <div class="tip-option">                     {{ choice.tag }} {{ choice.choice_label }}                 </div>             {% endfor %}         </div>         <br>         <label for="{{ form.num_people.id_for_label }}">Number of People</label>         {{ form.num_people }}         <br>                  <button type="submit">Calculate</button>     </form> </body> </html> 

result.html: This HTML code creates a result page for the Tip Calculator, presenting calculated tip and total amounts per person. The design features a centered layout with clear typography and a link to calculate another tip. Amounts are displayed with the currency symbol "₹" for Indian Rupees.

HTML
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Tip Calculator Result</title>     <style>         body {             font-family: 'Arial', sans-serif;             background-color: #f4f4f4;             margin: 0;             padding: 0;             display: flex;             align-items: center;             justify-content: center;             height: 100vh;         }          h2 {             text-align: center;             color: #333;         }          .result-container {             background-color: #fff;             border-radius: 10px;             padding: 20px;             width: 250px;             box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);             text-align: center;         }          .result-text {             font-size: 18px;             margin-bottom: 15px;             font-family: 'Times New Roman', Times, serif;         }          .result-value {             font-size: 20px;             font-weight: bold;             color: #4caf50;         }          .calculate-another-link {             display: block;             margin-top: 20px;             text-align: center;             text-decoration: none;             color: #333;         }          .calculate-another-link:hover {             text-decoration: underline;         }     </style> </head> <body>     <div class="result-container">         <h2>Result</h2>         <p class="result-text">Tip / Person: <span class="result-value">&#8377; {{ calculations.tip_amount }}</span></p>         <p class="result-text">Total / Person: <span class="result-value">&#8377; {{ calculations.total_amount_per_person }}</span></p>         <!-- Add any other information you want to display -->         <a class="calculate-another-link" href="{% url 'tip_calculator' %}">Calculate Another Tip</a>     </div> </body> </html> 

Deployment 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
2024-01-3108-34-27online-video-cuttercom-ezgifcom-video-to-gif-converter



Next Article
Python | Loan calculator using Tkinter
author
sourabhsahu33
Improve
Article Tags :
  • Python
  • Django
  • Python Django
  • Django-Projects
Practice Tags :
  • python

Similar Reads

  • Calculate CGPA using Python Django
    This article demonstrates how to build a CGPA calculator and display the results using Django. Initially, we establish a login system to ensure security. Users must first register for an account and then log in to access the calculator. After logging in, users can input their subject names, CGPA, an
    11 min read
  • Python | Loan calculator using Tkinter
    Prerequisite: Tkinter Introduction Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest
    5 min read
  • Ratio Calculator using PyQt5
    In this article we will see how we can create a ratio calculator using PyQt5. Ratio is a contrast, which exists between two particular numbers, is defined as ratio. This ratio calculator is developed to compute this contrast and find out the relationship between these numbers. Below is how the calcu
    5 min read
  • Build Calculator App Using Django
    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 ha
    3 min read
  • Realtime chat app using Django
    Chat Room has been the most basic step toward creating real-time and live projects. The chat page that we will create will be a simple HTML boilerplate with a simple h1 text with the name of the current user and a link to log out to the user who is just logged in. You may need to comment on the line
    11 min read
  • Creating Golden Ratio Calculator using PyQt5
    In this article we will see how we can create a golden ratio calculator using PyQt5. In mathematics, two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. The value of golden ratio is 1.61803398875. Below is how the golden ra
    6 min read
  • Event Countdown Timer using Django
    To create anticipation and excitement for these events, one useful tool is a countdown timer that displays the time remaining until the event starts. In this article, we'll explore how to build an event countdown timer using Django, a popular Python web framework. Event Countdown Timer using DjangoA
    4 min read
  • Loan Calculator using PyQt5 in Python
    In this article, we will see how we can create a loan calculator using PyQt5, below is an image that shows how is the loan calculator will look like : PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because
    5 min read
  • Joke Application Project Using Django Framework
    Django is a high-level Python-based Web Framework that allows rapid development and clean, pragmatic design.  It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. Today we will create
    2 min read
  • Quiz Application using Django
    In this article, we will create the Django Quiz Application generally the Django Quiz App is a versatile and interactive web application designed to revolutionize learning and assessment. Created to address the need for engaging and adaptable online quizzes, it offers educators, businesses, and indi
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences