Running Total in Django Template

231 views Asked by At

I listed debit and credit for my account transactions. Now I want to running total in last column by debit subtracted by credit added with previous arrived amount as running total (as you know). Thanks for your support.

my view:

 def listaccounttrans(request):
    alltrans = FinTransDetail.objects.all()
    context = {'alltrans': alltrans}
    return render(request, 'waccounts/list_account_trans.html', context)

my html:

 {{% extends 'wstore_base_generic.html' %}}
 {% block content %}
 <h3>Table</h3>
 <div>

 <table id="customers" >
 <thead>

  <tr>
     <td>AcctCode</td>
     <td>TransNo</td>
    <td>TransDate</td>
    <td>AcctDetail</td>
    <td>Debit</td>
    <td>Credit</td>
    <td>Balance</td>
  </tr>
</thead>
<tbody>
{% for acct in alltrans%}
  <tr>
    <td>{{ acct.fd_acct }}</td>
    <td>{{ acct.fd_no}}</td>
    <td>{{ acct.fd_no.fh_dt}}</td>
    <td>{{ acct.fd_no.fh_detail }}</td>
    <td>{{ acct.fd_debit }}</td>
    <td>{{ acct.fd_credit }}</td>
   <td>{{ acct.fd_no}}</td> # needs running total here#
  </tr>
  {% endfor %}
   </tbody>
   </table>
   </div>
   {% endblock %}

my template is showing now:

 AcctCode   TransNo TransDate   AcctDetail  Debit   Credit     Balance
 1101         94    May 18, 2021    Detail  11.00   0.00        94 (needs to be replaced with 
 1101         94    May 18, 2021    Detail  0.00    11.00       94  running balance)

                                                                  [total balance]
1

There are 1 answers

0
Madukkur-com Madukkur On

Thanks to E Paul. My revised view is

 def listaccounttrans(request):
     alltrans = FinTransDetail.objects.all()
     openbal=0
     for item in alltrans:
          openbal=openbal+(item.fd_debit-item.fd_credit)
          item.balance=openbal
    
    context = {'alltrans': alltrans}
    return render(request, 'waccounts/list_account_trans.html', context)

Now you can refer in template:

 <td>{{ acct.balance }}</td>