Django-input-field-dropdown-for-receiver-customized-based-on-sender

I am trying to make my dropdown list for the receiver in which the sender’s id/name won’t be included. I guess this is not a case of chained dropdown which has been answered previously. Maybe ajax is needed to be used here, but I am not understanding the exact code of ajax, if it is to be used. Below are my template file, views.py file, and models.py file.

home.html file

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'Bank_App/css/styles.css' %}" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    

    <script src="https://code.jquery.com/jquery-3.6.0.js"
        integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

    

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous">
    </script>


</head>

<body>
    <div class="container">
        <center>
            <h2>Customer Details</h2>
        </center>


        <table>
            <tr>
                <th>Sr. No.</th>
                <th>Customer Id</th>
                <th>Customer Email</th>
                <th>Account Balance</th>
                <th>Send Money</th>
            </tr>
            {% for customer in customer_details %}
            <tr>
                <td id="customer_pk">{{customer.pk}}</td>
                <td id="customer_id">{{customer.customer_id}}</td>
                <td id="customer_email">{{customer.customer_id.email}}</td>
                <td id="customer_acc_balance">{{customer.account_balance}}</td>
               
                <td>                    
                    <center><button type="button" class="btn btn-primary btnDemo" data-bs-toggle="modal"
                            data-bs-target="#exampleModal" id="send" data-name={{customer.customer_id}}
                            data-balance={{customer.account_balance}}>
                            Send Money
                        </button>
                    </center>

                </td>
            </tr>
            {% endfor %}
        </table>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Transfer Money</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <h6 id="modal_body"></h6>
                    <center>
                        <form id="transfer-money-form">
                            {% csrf_token %}
                            <label for="senderId">Sender Id :</label>                            
                            <b><input type="text" id="senderId" name="senderId" disabled></b><br>
                            Account Balance : <b><span id="account_bal" name="account_bal"></b></span><br><br>

                            <div class="input-group mb-3">

                                <label for="receiverId">Receiver Id :</label>


                                <select class="form-select d-md-inline" id="receiverId">
                                    <option value="" disabled selected hidden></option>
                                    {% for i in customer_details %}
                                    <option value="{{i.customer_id}}">{{i.customer_id}}</option>
                                    {% endfor %}                                    
                                </select>
                            </div>
                            Amount : <span><input type="number" step="0.01" min=0 id="amt_transfer"></span>                           

                            <div>
                                <button type="submit" class="btn btn-success btn-sm" data-toggle="modal"
                                    data-target="#exampleModal" id="submit" value="SUBMIT">
                                    Submit
                                </button>
                            </div>
                        </form>
                    </center>
                </div>                
            </div>
        </div>
    </div> 


    <script type="text/javascript">
        $('.btnDemo').click(function () {    
            senderID = $(this).data('name');
            $('#senderId').val(senderID);        
            $('#account_bal').html($(this).data('balance'));
            
            
        });        

        $(document).on('submit', '#transfer-money-form', function (e) {
            e.preventDefault();    
            $.ajax({
                type: 'POST',
                url: '/transaction',
                data: {
                    sender_id: $('#senderId').val(),
                    receiver_id: $('#receiverId').val(),
                    amt_transfer: $('#amt_transfer').val(),
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function () {
                    alert("Transaction done!");
                    console.log("this ran!");
                }    
            });
        });
    </script>

</body>    
</html>

views.py file

from django.shortcuts import render

from django.http import HttpResponse, request

from . models import Customer_Detail, Transaction

# Create your views here.

def home(request):

    context = {

        'customer_details': Customer_Detail.objects.all()

    }

    

    return render(request, 'Bank_App/home.html',context)

def transaction(request):

    if request.method == 'POST':        

        senderId = request.POST['sender_id']

        print(senderId)        

        receiverId = request.POST.get('receiver_id')

        print(receiverId)

        amt_transfer = request.POST['amt_transfer']

    Transaction.objects.create(

        sender_id = senderId,

        reciever_id = receiverId,

        amt_transfer = amt_transfer

    )

     

    return HttpResponse('')

models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Customer_Detail(models.Model):  
    
    customer_id = models.ForeignKey(User, on_delete=models.CASCADE)   
    account_balance = models.FloatField()
    def __str__(self) :
        return self.customer_id.email



class Transaction(models.Model):      
    sender_id = models.CharField(max_length=255)
    reciever_id = models.CharField(max_length=255)
    amt_transfer = models.FloatField()
    transaction_date = models.DateTimeField(default = timezone.now)    
    
    def __str__(self) :
        return str(self.pk)

Thanks in advance :slight_smile:

You need to filter the values in customer_details. You can do that by adding a filtered list to the context in the view or by filtering in the template. If you filter in the template, just check for the appropriate customer here

and don’t show their details using a conditional.

If this has to be dynamic and you don’t know the customer that does not need displayed in advance, you can use some custom JS to make the recipient list (filter out what is unnecessary) or you can rethink your Django app and require the user to login and filter them out of the recipient list in advance (in the view context, for instance). If you have a lot of items like this that need to change dynamically on the front end, consider letting Django serve an API and use a front-end framework in your pages (vue, react, etc.)

Also, Django will handle form submission and validation for you, so unless you are doing something special (or using a front-end framework), you don’t really need the jquery script at the end to submit the form.

Thank you so much for all the suggestions. I am trying to update the context thing and will let you know if it works!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.