0

I have a Django app as shown in image my Django app

I want to use the delete icon to show confirmation popup and then delete the selected entry from the database. In general, I would use AJAX call and JS for this. How can I achieve this in Django?

Template code: index.html

    <!DOCTYPE html>
{% load staticfiles %}
{% load pm_extras %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Portfolio</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="{% static 'portfolio_management_statics/css/style.css' %}">
</head>
<body>
    <div class="container">
        <h1>Portfolio</h1>
        <form method="post">{% csrf_token %}
<!--            <label for="stock-name">Stock Name: </label><input id="stock-name" name="stock-name" type="text">-->
<!--            <label for="trans-price">Transaction Price </label><input id="trans-price" type="number">-->
<!--            <label for="trans-date">Transaction Date </label><input id="trans-date" type="date">-->
<!--            <label for="quantity">Quantity </label><input id="quantity" type="number">-->
            {{ stock_add_form.as_p }}
            <input type="submit" value="Add Stock">
        </form>
    </div>
    <div class="container">
        <table>
            <tr>
                <th>Stock Name</th>
                <th>Transaction Price</th>
                <th>LTP</th>
                <th>Transaction Quantity</th>
                <th>Transaction Date</th>
                <th>Invested Value</th>
                <th>Current Market Value</th>
                <th>Capital Gains</th>
                <th>Capital Gains %</th>
                <th></th>
            </tr>
            {% for stock in portfolio %}
            <tr>
                <td>{{ stock.stock_name }}</td>
                <td>{{ stock.trans_price1 }}</td>
                <td>{{ stock_ltps | dict_key:stock.stock_name }}</td>
                <td>{{ stock.trans_quantity1 }}</td>
                <td>{{ stock.trans_date }}</td>
                <td>{{ stock_invested_value | dict_key:stock.stock_name }}</td>
                <td>{{ stock_current_value | dict_key:stock.stock_name }}</td>
                <td>{{ stock_gains | dict_key:stock.stock_name }}</td>
                <td>{{ stock_gains_per | dict_key:stock.stock_name }} %</td>
                <td><i class="glyphicon glyphicon-trash"></i></td>
            </tr>
            {% endfor %}
            <tr><th colspan="5">Total</th><th>{{total.total_investment}}</th><th>{{total.total_current_market_value}}</th>
                <th>{{total.total_stock_gain}}</th><th>{{total.total_stock_gain_per}} %</th></tr>
        </table>
    </div>
    <script
      src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
      integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8="
      crossorigin="anonymous"></script>
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>

2 Answers2

2

The code will be too much to type, but in thinking, The delete button is going to be a button with 'onClick' with 'confirm' HTML field upon which run an ajax function. The ajax call will have 'data' field with row id to delete and upon completion, in 'sucess' ajax field write a for loop to the update table entries using inner HTML attribute in js.

Harsh Nagarkar
  • 697
  • 7
  • 23
0

As @harsh described, I found that AJAX is the best way to make asynchronous changes in the database. But reflecting these changes without reloading is still an unfinished task.

I guess front-end library like react is the only solution for this.

views.py

def delete_stock_from_portfolio(request):
Portfolio.objects.filter(stock_name="Comfort Fincap").delete()
payload = {'success': True}
return HttpResponse(json.dumps(payload), content_type='application/json')

script

function post_ajax() {
            var xhr = new XMLHttpRequest()
            xhr.open('POST', 'delete', true)
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
            xhr.setRequestHeader("X-CSRFToken", csrftoken)

            xhr.onload = function() {
                if (this.status == 200) {
                    console.log(this.responseText)
                }
            }

            xhr.send()
        }

        function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');