简体   繁体   English

Django:user.save() 不保存更新到扩展

[英]Django: user.save() not saving updates to extended from

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.我在扩展表单中制作了余额字段,因为默认的 UserCreationForm 没有余额字段。 See the code below:请看下面的代码:

views.py视图.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模型.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 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.您必须保存正确的 object。

You are saving the user object but you have to save the account object, so you need to:您正在保存user object 但您必须保存account object,因此您需要:

user.account.balance = user.account.balance - int(withdrawAmount)
user.account.save()

This should work.这应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM