Open In App

Receipt Print with GUI using Django

Last Updated : 04 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will guide you through creating a Recipe Print GUI. To achieve this, we first establish a login system, allowing sellers to create accounts through registration and subsequent login. Once logged in, we provide a straightforward form where sellers input the name, price, and quantity of materials. After clicking the “Add” button, the system calculates the total by multiplying the price and quantity, and the sum is displayed in a table at the bottom. Sellers can conveniently manage their data by accessing options to delete or update entries with a single click. When ready, they can generate bills effortlessly by clicking the “Generate Bill” button. Finally, sellers can log out with a simple click on the “Logout” button.

Receipt Print with GUI using Django

Sellers can conveniently manage their data by accessing options to delete or update entries with a single click. When ready, they can generate bills effortlessly by clicking the “Generate Bill” button. Finally, sellers can log out with a simple click on the “Logout” button.

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

file-for-GUI

file Structure

Setting Necessary Files

models.py: This Django model defines a Receipt with fields for user association, name, price, quantity, and total. It includes a foreign key to the User model and sets default values for the fields.

Python3




from django.db import models
from django.contrib.auth.models import User
 
class Receipt(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    name = models.CharField(max_length=100, default='something')
    price = models.IntegerField(default=0)
    quantity = models.IntegerField(default =0)
    total = models.IntegerField(default=0)


views.py: The functions in the view file collectively build a Django web application for managing receipt data, user accounts, and generating PDFs.

Python3




from django.shortcuts import render, redirect
from .models import Receipt 
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import logout
 
@login_required(login_url='/login/')
def receipts(request):
    if request.method == 'POST':
        data = request.POST
        name = data.get('name')
        price = data.get('price')
        quantity = data.get('quantity')
        total = float(price) * int(quantity)
 
        Receipt.objects.create(
            name = name,
            price=price,
            quantity=quantity,
            total=total
        )
        return redirect('/')
 
    queryset = Receipt.objects.all()
    if request.GET.get('search'):
        queryset = queryset.filter(
            name__icontains=request.GET.get('search'))
         
      # Calculate the total sum
    total_sum = sum(receipt.total for receipt in queryset)
    context = {'receipts': queryset, 'total_sum': total_sum}
    return render(request, 'receipts.html', context)
@login_required(login_url='/login/')
def update_receipt(request, id):
    queryset = Receipt.objects.get(id=id)
 
    if request.method == 'POST':
        data = request.POST  
        name = data.get('name')
        price = data.get('price')
        quantity = data.get('quantity')
        total = float(price) * int(quantity)
         
        queryset.name = name
        queryset.price = price
        queryset.quantity = quantity
        queryset.total = total
        queryset.save()
        return redirect('/')
 
    context = {'receipt': queryset}
    return render(request, 'update_receipt.html', context)
 
@login_required(login_url='/login/')
def delete_receipt(request, id):
    queryset = Receipt.objects.get(id=id)
    queryset.delete()
    return redirect('/')
 
def login_page(request):
    if request.method == "POST":
        try:
            username = request.POST.get('username')
            password = request.POST.get('password')
            user_obj = User.objects.filter(username=username)
            if not user_obj.exists():
                messages.error(request, "Username not found")
                return redirect('/login/')
            user_obj = authenticate(username=username, password=password)
            if user_obj:
                login(request, user_obj)
                return redirect('receipts')
            messages.error(request, "Wrong Password")
            return redirect('/login/')
        except Exception as e:
            messages.error(request, "Something went wrong")
            return redirect('/register/')
    return render(request, "login.html")
 
def register_page(request):
    if request.method == "POST":
        try:
            username = request.POST.get('username')
            password = request.POST.get('password')
            user_obj = User.objects.filter(username=username)
            if user_obj.exists():
                messages.error(request, "Username is taken")
                return redirect('/register/')
            user_obj = User.objects.create(username=username)
            user_obj.set_password(password)
            user_obj.save()
            messages.success(request, "Account created")
            return redirect('/login')
        except Exception as e:
            messages.error(request, "Something went wrong")
            return redirect('/register')
    return render(request, "register.html")
 
def custom_logout(request):
    logout(request)
    return redirect('login')
 
@login_required(login_url='/login/')
def pdf(request):
    if request.method == 'POST':
        data = request.POST   
        name = data.get('name')
        price = data.get('price')
        quantity = data.get('quantity')
        total = float(price) * int(quantity)
 
        Receipt.objects.create(
            name = name,
            price=price,
            quantity=quantity,
            total=total
        )
        return redirect('pdf')
 
    queryset = Receipt.objects.all()
 
    if request.GET.get('search'):
        queryset = queryset.filter(
            name__icontains=request.GET.get('search'))
         
      
    total_sum = sum(receipt.total for receipt in queryset)
 
    context = {'receipts': queryset, 'total_sum': total_sum}
    return render(request, 'pdf.html', context)


Creating GUI

login.html: This HTML code is for a basic login page within a Bootstrap-styled container. It includes fields for a username and password, a “Login” button, and a link to create a new account. The page uses some custom CSS for styling and includes external libraries for additional styling.

HTML




<!doctype html>
<html lang="en">
 
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <title>Job Portal</title>
</head>
<style>
    .text{
        color: green;
        font-weight: bold;
        font-family: 'Times New Roman', Times, serif;
      }
   
</style>
<body><br><br><br><br>
 
    
   <br><br>
     
    <div class="container  mt-4 bg-white col-md-3 card shadow p-3 " id="log">
        <div class="login-form">
            {% if messages %}
            {% for message in messages %}
            <div class="alert alert-success {{ message.tags }} mt-4" role="alert">
                {{ message }}
            </div>
            {% endfor %}
            {% endif %}
            <form action="" method="post">
                {% csrf_token %}
                <h3 class="text text-center"> GeeksforGeeks </h3>
                <h4 class="text-center" style="font-family: 'Times New Roman', Times, serif;">  Login </h4>
                <div class="form-group">
                    <input type="text" class="form-control" name="username" placeholder="Username" required
                        style="background-color: #fff; border: 1px solid #ddd; border-radius: 5px; padding: 10px;">
                </div>
                <div class="form-group mt-2">
                    <input type="password" class="form-control" name="password" placeholder="Password" required
                        style="background-color: #fff; border: 1px solid #ddd; border-radius: 5px; padding: 10px;">
                </div>
                <div class="form-group mt-2">
                    <button class="btn btn-success btn-block" style="margin-left: 138px;">Login ????</button>
                </div>
                <br>
            </form>
            <p class="text-center" style="color: #555;"><a href="{% url 'register' %}" style="color: #007bff;">Create an
                    Account.➡️</a></p>
        </div>
    </div>
 
</body>
 
</html>


register.html: This HTML code is for a simple registration page. It includes fields for a username and password, a “Register” button, and a link to log in. The page uses Bootstrap and Font Awesome for styling and includes custom CSS for additional styling.

HTML




<!doctype html>
<html lang="en">
 
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <title>Job Portal</title>
</head>
 
<body>
 
    <style>
        .text{
            color: green;
            font-weight: bold;
            font-family: 'Times New Roman', Times, serif;
          }
 
    </style>
 
    <body>
        <br> <br><br><br><br><br>
 
        <div class="container mt-4   bg-white mx-auto col-md-3 card shadow p-3">
            <div class="login-form">
                {% if messages %}
                {% for message in messages %}
                <div class="alert alert-success {{ message.tags }}" role="alert">
                    {{ message }}
                </div>
                {% endfor %}
                {% endif %}
                <form action="" method="post">
                    {% csrf_token %}
                    <h3 class="text text-center"> GeeksforGeeks </h3>
                    <h4 class="text-center" style="font-family: 'Times New Roman', Times, serif;"> Register </h4>
                    <div class="form-group">
                        <input type="text" class="form-control" name="username" placeholder="Username" required>
                    </div>
                    <div class="form-group mt-2">
                        <input type="password" class="form-control" name="password" placeholder="Password" required>
                    </div>
                    <div class="form-group mt-2">
                        <button class="btn btn-success btn-block" style="margin-left: 117px;">Register ????</button>
                    </div>
                    <br>
                </form>
                <p class="text-center"><a href="{% url 'login' %}">Log In ➡️</a></p>
            </div>
        </div>
 
    </body>
 
</html>


receipt.html: This HTML template extends a base template, and it creates a form for users to add receipts with item details. It also displays a list of existing receipts in a table, allowing users to delete or update them. The page includes styling with Bootstrap and custom CSS for aesthetics and layout. Additionally, there are options to generate a bill and log out.

HTML




{% extends "base.html" %}
{% block start %}
 
<style>
  .text{
    color: green;
    font-weight: bold;
    font-family: 'Times New Roman', Times, serif;
  }.ok{
    color: white;
    text-decoration: none;
  }
  .ok:hover{
    color: white;
    text-decoration: none;
  }
</style>
 
<div class="container mt-5 col-6">
    <form class="col-6 mx-auto card p-3 shadow-lg" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <h3 class="text text-center"> GeeksforGeeks </h3>
        <br>
        <h4 style="font-family: 'Times New Roman', Times, serif;"> Create Receipt???? </h4>
        <hr>
        <div class="form-group">
          <label for="exampleInputEmail1">Item Name </label>
          <input type="text" name="name" class="form-control" required>
        </div>
        <div class="form-group">
          <label for="exampleInputEmail1">Price </label>
          <input name="price" type="number" class="form-control" required>
         </div>
        <div class="form-group">
          <label for="exampleInputPassword1">Quantity </label>
          <input name="quantity" class="form-control" type="number" required>
        </div>
        <button type="submit" class="btn btn-success">Add Data ????</button>
    </form>
    <hr>
    <div class="class mt-5">
        <form action="">
          <button class="btn btn-primary"> <a class="ok" href="{% url 'pdf' %}">Generate Bill </a></button>
          <button class="btn btn-danger"> <a class="ok" href="{% url 'logout' %}">Logout </a></button>
        </form>
 
        <table class="table mt-6">
            <thead>
                <tr>
                    <th scope="col">S.No. </th>
                    <th scope="col">Item name </th>
                    <th scope="col">Price </th>
                    <th scope="col">Quantity </th>
                    <th scope="col">Total </th>
                    <th scope="col">Actions ????</th>
                </tr>
            </thead>
            <tbody>
                {% for receipt in receipts %}
                <tr>
                    <th scope="row">{{forloop.counter}}</th>
                    <td>{{receipt.name}}</td>
                    <td> ₹{{receipt.price}}</td>
                    <td>{{receipt.quantity}}</td>
                    <td>  ₹{{receipt.total}}</td>
                    <td>
                        <a href="/delete_receipt/{{receipt.id }}" class="btn btn-danger m-2">Delete </a>
                        <a href="/update_receipt/{{receipt.id }}" class="btn btn-success">Update </a>
                    </td>
                </tr>
                {% endfor %}
                <tr>
                    <th colspan="4" class="text-right">Total Sum :</th>
                    <td>{{ total_sum }}</td>
                </tr>
            </tbody>
        </table>
    </div>
{% endblock %}


update_receipt.html: This HTML template is for updating data in a web application. It includes a form for editing details related to an item, with fields pre-filled using existing data. The page uses Bootstrap for styling and some custom CSS. Users can update the data by clicking the “Update Data” button.

HTML




{% extends "base.html" %}
{% block start %}
 
<style>
  .text{
    color: green;
    font-weight: bold;
    font-family: 'Times New Roman', Times, serif;
  }
</style>
 
<div class="container mt-5 col-5">
 
  <form class="col-6 mx-auto card p-3 shadow-lg" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <h3 class="text  text-center"> GeeksforGeeks </h3>
     
    <h4 style="font-family: 'Times New Roman', Times, serif; font-size:20px;">Update Data </h4>
    
    <div class="form-group">
      <label for="exampleInputEmail1">Item name </label>
      <input type="text" name="name" value="{{receipt.name}}" class="form-control" required>
    </div>
    <div class="form-group">
      <label for="exampleInputEmail1">Price </label>
      <input name="price" type="number" value="{{receipt.price}}" type="text" class="form-control" required>
    </div>
    <div class="form-group">
      <label for="exampleInputPassword1">Quantity </label>
      <input name="quantity" type="number" value="{{receipt.quantity}}" class="form-control"
        required>
    <br>
 
    <button type="submit" class="btn btn-danger">Update Data ????</button>
  </form>
 
 
</div>
 
{% endblock %}


pdf.html: This HTML template creates a receipt for a purchase with the following features:

  • It includes Bootstrap for styling and custom CSS.
  • Displays company details, item information, and a total sum.
  • Provides a “Generate Receipt” button that triggers the print functionality when clicked.
  • JavaScript is used to extract the receipt content and initiate printing.

The page offers a printable receipt for users to save or use for their records.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receipt</title>
 
    <!-- Add Bootstrap CSS Link -->
    <style>
        .invoice {
            text-align: center;
            margin-left: 33%;
        }
 
        .o123 {
            margin-top: 3%;
            margin-left: 1%;
        }
 
        .company {
            margin-left: 80%;
            margin-top: -20%;
        }
 
        .amount {
            margin-left: 76%;
        }
 
        .total {
            margin-left: 70%;
        }
 
        .sign {
            margin-top: 3%;
            margin-left: -13%;
        }
 
        .receipt-container {
            padding: 20px;
            border: 2px solid #000;
            border-radius: 10px;
            background-color: #fff;
            margin-top: 30px;
        }
 
        .receipt-header {
            text-align: center;
        }
 
        .receipt-title {
            font-size: 24px;
            color: #333;
        }
 
        .receipt-details {
            font-size: 16px;
            color: #555;
            margin-top: 20px;
        }
 
        .receipt-table {
            width: 100%;
            margin-top: 20px;
            border-collapse: collapse;
        }
 
        .receipt-table th,
        .receipt-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
 
        .receipt-total {
            font-size: 20px;
            font-weight: bold;
            color: #333;
            margin-top: 20px;
        }
 
        .receipt-footer {
            margin-top: 20px;
            font-size: 16px;
            color: #555;
        }
 
        .btn {
            margin-left: 48%;
            margin-top: 2%;
 
        }
 
        h2 {
            color: green;
 
        }
 
        img {
            width: 200px;
            height: 150px;
        }
        #date{
            margin-left: 120px;
            
        }
    </style>
</head>
 
<body>
 
    <div id="mn" class="container receipt-container col-8">
        <div class="receipt-header">
            <img src="https://i.ibb.co/FDKRRtN/gfg.jpg" alt="">
 
        </div>
      
 
        <div class="row" >
            <div class="col-xl-10" id="date">
 
                <br><br>
                <br><br>
                <ul class="list-unstyled company float-end">
                    <li style="font-size: 20px; "> <b>Address :</b></li>
                    <li>Noida,Uttar Pradesh</li>
                    <li>1800 258 4458</li>
                    <li>geeksforgeeks.org</li>
                </ul>
            </div>
        </div>
        <br><br>
        <table class="receipt-table">
            <thead>
                <tr>
                    <th>Description</th>
                    <th>Amount/Piece</th>
                    <th>Quantity</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
 
 
                {% for receipt in receipts %}
                <tr>
                
                  <td>{{receipt.name}}</td>
                  <td> ₹ {{receipt.price}}</td>
                  <td>{{receipt.quantity}}</td>
                  <td> ₹ {{receipt.total}}</td>
                          
               
              </tr>
                {% endfor %}
               
            </tbody>
        </table>
        <p class="receipt-total">Total Sum: ₹{{ total_sum }}</p>
        <div class="receipt-footer">
            <p>Thank you for your purchase!</p>
        </div>
    </div>
 
    <button onclick="myfun('mn')" type="button" class="btn btn-success btn1 ">Generate Receipt</button>
 
    <!-- Add Bootstrap JS and jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script type="text/javascript">
        function myfun(pa) {
            let d = document.getElementById(pa).innerHTML;
            document.body.innerHTML = d;
            window.print();
        }
    </script>
</body>
 
</html>


base.html: In this html file we write the code of the table and some basic margin padding which we apply in some html files for that we joint some html file with base.html file

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{page}}</title>
 
    <style>
        table {
            width: 80%;
            margin: 20px auto;
            border-collapse: collapse;
        }
 
        th,
        td {
            padding: 10px;
            text-align: left;
            border: 1px solid #ccc;
        }
 
        th {
            background-color: #f2f2f2;
        }
 
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
 
        tr:hover {
            background-color: #ddd;
        }
    </style>
</head>
 
<body>
 
    {% block start %}
    {% endblock %}
 
    <script>
        console.log('Hey Django')
    </script>
</body>
 
</html>


admin.py:Here we are registering our models.

Python3




from django.contrib import admin
from .models import *
from django.db.models import Sum
 
admin.site.register(Receipt)


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

update-base

base.html



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads