I am making a bank transaction system and I want the user to withdraw and deposit the amount into their account. I made the balance field in an extended form as the default UserCreationForm does not have a balance field. See the code below:
views.py
@login_required(redirect_field_name='login-page')
def dashboard(request):
if request.method == 'POST':
withdrawAmount = request.POST.get('withdraw')
depositAmount = request.POST.get('deposit')
print(withdrawAmount, depositAmount)
user = User.objects.get(username=request.user.username)
print(user)
if withdrawAmount == None and depositAmount == None:
return redirect('dashboard')
messages.info(request, "Amount empty!")
elif depositAmount == None:
user.account.balance = user.account.balance - int(withdrawAmount)
user.save()
elif withdrawAmount == None:
pass
customer = User.objects.all()
return render(request, 'bankapp/dashboard.html', {'customer': customer})
models.py
from django.db import models
from django.contrib.auth.forms import User
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
balance = models.IntegerField()
def __str__(self):
return self.user.username
forms.py
from django import forms
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm, User
from .models import Account
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=128, help_text='Input valid email')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
class AccountForm(forms.ModelForm):
class Meta:
model = Account
fields = ('balance',)
The code works perfectly and gives no errors but the balance does not get updated in the database. Any help would be greatly appreciated!
You have to save the proper object.
You are saving the user
object but you have to save the account
object, so you need to:
user.account.balance = user.account.balance - int(withdrawAmount)
user.account.save()
This should work.