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:
Transactions in Mongoose
Next article icon

Django Transaction System with Database Updates

Last Updated : 18 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In today's digital age, transaction systems play a pivotal role in various industries, from e-commerce platforms to banking and beyond. These systems are responsible for handling financial operations, ensuring data accuracy, and providing a seamless user experience. One of the most powerful tools for building transaction systems is Django, a high-level Python web framework. In this tutorial, we will explore how to create a transaction system in Django and demonstrate the process of updating a database during transactions.

Django is known for its robustness, security features, and ease of development, making it an ideal choice for building reliable and scalable transaction systems. so let's start

Creating Django Transaction System with Database Updates

To install Django follow these steps.

Starting the Project Folder

To start the project use this command

django-admin startproject dj
cd dj

To start the app use this command

python manage.py startapp home

Now add this app to the 'settings.py'

Setting up Necessary Files

model.py: The "models.py" file within the "home" app defines the structure of our database tables. In our example, we've created a Payment model.

Python3
from django.db import models  class Transaction(models.Model):     user = models.CharField(max_length=100, unique=True)     amount = models.IntegerField(default=100) 

views.py: We import necessary modules, including render, messages, and the Payment model.The home function handles HTTP POST requests, extracting user names and the transfer amount from the request.To ensure that all database operations within the block are atomic, we use the transaction.atomic() context manager. If any operation within the transaction fails, the entire block is rolled back, preserving the database's consistency.We update user account balances based on the transfer amount and display success or error messages to the user.

Python3
from django.shortcuts import render from django.contrib import messages from .models import Transaction from django.db import transaction   def home(request):     if request.method == 'POST':         try:             one = request.POST.get('one')             two = request.POST.get('two')             amount = int(request.POST.get('amount'))                           # Start a database transaction block             with transaction.atomic():                 user_one_Transaction_obj = Transaction.objects.get(user=user_one)                 user_two_Transaction_obj = Transaction.objects.get(user=user_two)                                       user_one_Transaction_obj.amount -= amount                 user_one_Transaction_obj.save()                                       user_two_Transaction_obj.amount += amount                 user_two_Transaction_obj.save()                           messages.success(request, "Amount transferred successfully")         except Exception as e:             messages.error(request, f"An error occurred: {e}")           return render(request, 'home.html') 

Creating GUI

home.html: This template defines the structure of the web page that users will interact with when they access the root URL.

HTML
<!DOCTYPE html> <html lang="en">   <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <!-- Include Bootstrap CSS from CDN -->     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">     <title>Hello, World</title> </head> <style>     .gfg{         color: green;         margin-left: 35%;              } </style>   <body>     <div class="container mx-auto mt-5 pt-2 col-7">         <h1 class="gfg">Geeksforgeeks </h1>         {% if messages %}         {% for message in messages %}         <div class="alert alert-info">             {{message}}         </div>         {% endfor %}         {% endif %}         <form method="POST">             {% csrf_token %}             <div class="form-group">                 <label for="userOne">User One</label>                 <input type="text" name="one" class="form-control" id="userOne" placeholder="Enter User One">             </div>             <div class="form-group">                 <label for="userTwo">User Two</label>                 <input type="text" name="two" class="form-control" id="userTwo" placeholder="Enter User Two">             </div>             <div class="form-group">                 <label for="amount">Amount</label>                 <input type="text" name="amount" class="form-control" id="amount" placeholder="Enter Amount">             </div>             <button type="submit" class="btn btn-primary">Submit</button>         </form>     </div> </body>   </html> 

admin.py: Here we are registering the models.

Python3
from django.contrib import admin from .models import Transaction   admin.site.register(Transaction) 

urls.py: We import essential modules such as admin, path, and the views module from our "home" app.The urlpatterns list contains URL patterns that define how different URLs are routed to specific views. In our example, we've set up an admin URL and a root URL mapping to the 'home' view

Python3
from django.contrib import admin from django.urls import path from home import views   urlpatterns = [     path("admin/", admin.site.urls),  # Admin URL     path("", views.home),  # Root URL maps to the 'home' view with the name 'home'     # Add more URL patterns here as needed ] 

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



Conclusion

In conclusion, transaction atomicity is a fundamental concept in database management and plays a crucial role in maintaining the integrity of your database operations. By creating a Django project, defining models, and understanding how to implement transaction atomicity, you are well-equipped to build robust and reliable web applications in Django. This ensures that your users can trust the consistency and accuracy of their data interactions, leading to a better user experience and increased reliability in your web applications.


Next Article
Transactions in Mongoose
author
prathamsahani0368
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Python Django
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

  • Transaction Atomic With Django
    In this article, we will explore the significance and application of transaction atomic() in Django. We'll delve into how this feature aids in maintaining data integrity and why it is an indispensable tool for developers working with databases. Understanding Database TransactionsBefore we delve into
    4 min read
  • What are transactions in Django?
    In this article, we will explore the concept of transactions in Django, using a specific project as our reference point. We will delve into the process of executing transactions in Django and discuss the implementation of the same on the backend of the Django framework the end of this article, reade
    10 min read
  • Update View - Function based Views Django
    Update View refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database for example, updating an article at geeksforgeeks. So Update view must display the old data in the form and let user update the data
    4 min read
  • Django ORM - Inserting, Updating & Deleting Data
    Django lets us interact with its database models, i.e. add, delete, modify, and query objects, using a database-abstraction API called ORM(Object Relational Mapper). This article discusses all the functional operations we can perform using Django ORM. Prerequisite: Django models Django ORM Django's
    3 min read
  • Transactions in Mongoose
    Mongoose Transactions allows to execute multiple database operations within a single transaction, ensuring that they are either all successful or none of them are. Mongoose provides powerful tools to manage transactions effectively. Transactions in MongooseStep 1: First, make sure you have Mongoose
    5 min read
  • Atomic Transactions in OS
    In the dynamic OS environment, data consistency and reliability are critical. One of the main mechanisms that help this stability is so-called atomic transactions. Atomic transactions are key in maintaining the integrity of data to ensure that operations on that data occur either completely or not a
    10 min read
  • How to fix 'django.db.transaction.TransactionManagementError'
    The 'django.db.transaction.TransactionManagementError' error surfaces when our project deals with the concept of transactions in database management systems, and something goes amiss within this process. In this article, we'll acquaint ourselves with this error, delve into its common causes, and exp
    3 min read
  • Transaction in DBMS
    In a Database Management System (DBMS), a transaction is a sequence of operations performed as a single logical unit of work. These operations may involve reading, writing, updating, or deleting data in the database. A transaction is considered complete only if all its operations are successfully ex
    10 min read
  • What is Transaction Server?
    A computer network is a framework that associates various autonomous computers to share data (information) and assets. The incorporation of computers and other various gadgets permits clients to communicate without any problem. It is a collection of at least two computer systems that are connected t
    5 min read
  • UpdateView - Class Based Views Django
    UpdateView refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database, for example, updating an article at geeksforgeeks. We have already discussed basics of Update View in Update View – Function based V
    3 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