title: Bank ATM ledger in Django - - deposit, withdrawal, balance
body: <p>I’m trying to build a rudimentary interactive ATM machine ledger prototype demo in Python with Django.</p>
  <p><a href="https://i.imgur.com/pl6EJ75.jpg" rel="nofollow noreferrer">Here is what my web app currently looks like</a>.</p>
  <p>The intended basic functionality I am trying to create right now is to have the web visitor (banking client) enter the amount of cash in the input field and then click: “Deposit” or ”Withdraw”. Say for example the client deposits $20.00, the amount should appear in the HTML table under the “Credits” column and the “Running Balance” column should reflect that as well, like anyone would expect a typical ATM and accounting ledger to behave. The end goal is to have unique timestamps and transaction IDs to generate with each transaction, but for now I am focused on just getting the ‘running balance’ variable (rightmost column) to update when the web visitor inputs an amount and clicks “Deposit”.  Currently, when a web visitor enters $20.00 as the amount in the box and then clicks “Deposit”, since I’ve got a print statement inside my <code>views.py</code>, the Django terminal shows: <code>&lt;QueryDict: {'csrfmiddlewaretoken': ‘&lt;redacted&gt;'], 'amount': ['20.00'], 'transaction': ['Deposit']}&gt;</code>. So an amount is being accepted and processed. But the Running Balance remains $0.00, which is what I am trying to solve.</p>
  <p><strong>forms.py</strong>:</p>
  <pre><code>from django import forms
   
  class AmountForm(forms.Form):
     amount = forms.DecimalField(label='Amount', max_digits=10, decimal_places=2)
     # deposit = forms.DecimalField(label='Deposit', max_digits=10, decimal_places=2)
     # withdraw = forms.DecimalField(label='Withdraw', max_digits=10, decimal_places=2)
  </code></pre>
  <p><strong>views.py</strong>:</p>
  <pre><code>from django.shortcuts import render
  from django.http import HttpResponseRedirect,HttpResponse
  from .models import Account, Transactions
  # Create your views here.
  from .forms import AmountForm
   
  def index(request):
     # Starting balance variable initialization:
     balance = 0
     context = {'balance': balance}
     # Import `Account` model data:
     data = Account.objects.all().order_by('-inception_date')
     # If this is a POST request we need to process the form data:
     print(request.POST)
     if request.method == 'POST':
         # Create a form instance and populate it with data from the request:
         form = Transactions(request.POST)
         # Check whether it's valid:
         if form.is_valid():
             # Process the data in form.cleaned_data as required:
             amount = form.cleaned_data['amount']
             if request.POST['transaction'] == 'Deposit':
                 balance = balance + amount
                 context.update({'balance': balance,})
             if request.POST['transaction'] == 'Withdraw':
                 balance = balance - amount
                 context.update({'balance': balance,})
             # Redirect to a new URL:
             return render(request, 'telagents/home.html', {'form': form, 'data':data, 'context': context,})
   
     # If a GET (or any other method) we'll create a blank form:
     else:
         form = AmountForm()
   
     return render(request, 'telagents/home.html', {'form': form, 'data':data, })
  </code></pre>
  <p><strong>models.py</strong>:</p>
  <pre><code>from django.db import models
  from datetime import datetime
  # from pytz import timezone
  import decimal
  from decimal import Decimal
  from random import randint
  from django.forms import ModelForm
  from telagents.forms import AmountForm
   
  class Account(models.Model):
     #### Static data elements :
     interest = models.DecimalField(max_digits=6, decimal_places=3) # Percent
     inception_date = models.DateTimeField('Client since (inception date)')
     first_name = models.CharField(max_length=30)
     last_name = models.CharField(max_length=30)
     account_number = models.BigIntegerField()
     #### Interactive and dynamic data points :
     debit = models.DecimalField(max_digits=12, decimal_places=2)
     credit = models.DecimalField(max_digits=12, decimal_places=2)
     balance = models.DecimalField(max_digits=12, decimal_places=2)
     amount = models.DecimalField(max_digits=12, decimal_places=2)
     trans_timestamp = models.DateTimeField(auto_now=False, auto_now_add=False)
     trans_id = models.BigIntegerField()
   
     def client_since(self):
         # a = self.pub_date.timezone.now(&quot;US&quot;)
         # b = pytz.timezone(&quot;US&quot;)
         return self.inception_date.strftime(&quot;%A %d %B %Y @ %I:%M:%S %p&quot;)
    
     def __str__(self):
         return f&quot;{self.first_name} {self.last_name}'s bank account.&quot;
   
  class Transactions(ModelForm):
     class Meta:
         model = Account
         fields = ['amount',]
  </code></pre>
  <p>As you can see at the bottom of the models.py above, I attempt to use a <code>ModelForm</code>. The only field is amount. For the model class variable, I use <code>Account</code> which in turn inherits the properties of the <code>Account</code> class defined above it through polymorphism. But this isn’t really what I am trying to do. Instead I wish to actually inherit the <code>amount</code> property defined in the <code>AmountForm</code> class as defined in <code>forms.py</code>. But when I change <code>Account</code> to <code>AmountForm</code>, Django throws an error saying : <code>AttributeError: type object 'AmountForm' has no attribute '_meta'</code></p>
  <p><strong>templates/home.html</strong>:</p>
  <pre><code> &lt;body&gt;
    {% block content %}
  
      &lt;br&gt;&lt;br&gt;
  
  {% for data_obj in data %}
      &lt;center&gt;
      Client Name : {{data_obj.first_name}} {{data_obj.last_name}}
          &lt;br&gt;
      Bank Account Number : {{data_obj.account_number}}
          &lt;br&gt;
      Client Since : {{ data_obj.inception_date }}
          &lt;br&gt;        
      Interest Rate : {{data_obj.interest}} %
      &lt;/center&gt;
  {% endfor%}
  
  &lt;br&gt;&lt;br&gt;
  &lt;center&gt;
  &lt;form action=&quot;{% url 'index' %}&quot; method=&quot;post&quot;&gt;
     {% csrf_token %}
     {{ form }}
   &lt;input type=&quot;submit&quot; value=&quot;Deposit&quot; name=&quot;transaction&quot; &gt;
   &lt;input type=&quot;submit&quot; value=&quot;Withdraw&quot; name=&quot;transaction&quot;&gt;
  &lt;/form&gt;
  &lt;/center&gt;
   
  &lt;center&gt;
  &lt;table class=&quot;GeneratedTable&quot;&gt;
    &lt;thead&gt;
     &lt;tr&gt;
       &lt;th&gt;Type&lt;/th&gt;
       &lt;th&gt;Timestamp&lt;/th&gt;
       &lt;th&gt;Trans ID #&lt;/th&gt;
       &lt;th&gt;Merchant&lt;/th&gt;
       &lt;th&gt;Debits&lt;/th&gt;
       &lt;th&gt;Credits&lt;/th&gt;
       &lt;th&gt;Running Balance&lt;/th&gt;
     &lt;/tr&gt;
   &lt;/thead&gt;
    &lt;tbody&gt;
     &lt;tr&gt;
     {% for trans_objs in data %}
       &lt;td&gt;(null)&lt;/td&gt;           
       &lt;td&gt;{{ trans_objs.trans_timestamp }}&lt;/td&gt;     
       &lt;td&gt;{{ trans_objs.trans_id }}&lt;/td&gt;     
       &lt;td&gt;Big Bank ATM&lt;/td&gt;
       &lt;td&gt;{{ trans_objs.debit }}&lt;/td&gt;
       &lt;td&gt;{{ trans_objs.credit }}&lt;/td&gt;     
       &lt;td&gt;{{ trans_objs.balance }} &lt;/td&gt;
     {% endfor %}    
     &lt;/tr&gt;
   &lt;/tbody&gt;
    &lt;tbody&gt;
     &lt;tr&gt;
     {% for trans_objs in context %}
       &lt;td&gt;(null)&lt;/td&gt;           
       &lt;td&gt;(null)&lt;/td&gt;     
       &lt;td&gt;(null)&lt;/td&gt;     
       &lt;td&gt;ATM&lt;/td&gt;
       &lt;td&gt;(null)&lt;/td&gt;
       &lt;td&gt;(null)&lt;/td&gt;     
       &lt;td&gt;{{ trans_objs.amount }} &lt;/td&gt;
     {% endfor %}    
     &lt;/tr&gt;
   &lt;/tbody&gt;
   
  &lt;/table&gt;
  &lt;/center&gt;
  
  {% endblock %}
  
  &lt;/body&gt;
  </code></pre>
  <p>As you can see here, I’ve got two rows within Jinja for loops. The first one just positions static information. Those are mostly just placeholders. All that data showing is entered in the Admin Dashboard.  It's static. In the second row is my best attempt at extrapolating the <code>balance</code> variable from the <code>context</code> dictionary in the <code>views.py</code> dynamically. But it doesn't work. It's empty as you can see in the screenshot I shared way at the top of this question.</p>
  <p>What do I need to change in my <code>views.py</code> to get Django to accept user form input in my template to complete the simple mathematical operation of adding the amount to the balance entered by the user and then having it updated in the HTML table?</p>
  <p>Resources I've used so far:</p>
  <ul>
  <li>To build my <code>views.py</code> above I leveraged <a href="https://docs.djangoproject.com/en/4.0/topics/forms/" rel="nofollow noreferrer">the official Django doc for creating forms</a>.</li>
  <li>To create my <code>Transactions</code> class, I leveraged <a href="https://ttps://docs.djangoproject.com/en/4.0/topics/forms/modelforms/" rel="nofollow noreferrer">the Django doc for model forms</a>.</li>
  </ul>