Open In App

Django Transaction System with Database Updates

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads