Django Transaction System with Database Updates
Last Updated : 18 Mar, 2024
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.
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