使用表单和其他来源的数据填充模型字段

时间:2017-03-07 15:25:27

标签: django

我有一个代表用户财务帐户的模型:

class Account(models.Model):
    currencies_list = [currency.alpha_3 for currency in pycountry.countries]
    currencies_tuples = ((currency, currency) for currency in currencies_list)

    user = models.ForeignKey(User)
    name = models.CharField(max_length=50)
    currency = models.CharField(max_length=3, choices=currencies_tuples)
    initial_balance = models.DecimalField(max_digits=10, decimal_places=2)
    current_balance = models.DecimalField(max_digits=10, decimal_places=2)

我想允许用户使用以下视图创建新帐户:

def new_account(request):
    if request.method == "POST":
        form = AccountForm(request.POST)
        if form.is_valid():
            account = form.save(commit=False)
            account.save()
            return redirect('index')
    else:
        form = AccountForm()
        return render(request, 'expenses/new_account.html', {'form': form})

并形成:

class AccountForm(ModelForm):
    class Meta:
        model = Account
        fields = ['name', 'currency', 'initial_balance']

我只是让用户填写三个字段:namecurrencyinitial_balance。我希望字段usercurrent_balance自动填充:user通过复制当前记录的用户ID和current_balance,方法是复制用户为initial_balance字段提供的值。

我可以请你指出正确的方向吗?

1 个答案:

答案 0 :(得分:1)

if form.is_valid():
    account = form.save(commit=False)
    account.user = request.user
    account.current_balance = form.cleaned_data.get('initial_balance')
    account.save()
    return redirect('index')