Django-ModelForm-初始值

时间:2019-03-20 20:31:24

标签: django modelform

我正在使用Modelforms,并且想设置“ feeder”字段的初始值。我收到以下类型错误:“以10为基数的int()的无效文字:'None'”可能是什么问题?

非常感谢大家

forms.py:

class CashFlowForm(forms.ModelForm):
 class Meta:
    model = models.CashFlow
    fields = ['type', 'amount', 'description','date']
    widgets = {'date': DatePicker()}

views.py:

def create_cashflow(request, fundslug):

 funddetail = Fund.objects.get(slug=fundslug)

 if request.method == 'POST':
    cf = CashFlowForm(request.POST)
    cf.feeder = funddetail.feeder
    if cf.is_valid():
        instance_cf = cf.save()
        messages.success(request, 'Cash Flow successfully added!')
        return redirect('funds:create_cashflow', fundslug = fundslug) 
 else:
    cf = CashFlowForm()

 return render(request, 'funds/create_cashflow.html', {'cf': cf})

2 个答案:

答案 0 :(得分:0)

我认为 funddetail.feeder 返回无,或者您可以尝试

cf.cleaned_data['feeder'] = funddetail.feeder

答案 1 :(得分:0)

除非有外键,否则模型并不重要。对于类型错误,主要与模型字段从表单获取的值有关。

要在提交表单后分配值,请执行以下操作

if request.method == 'POST':
    cf = CashFlowForm(request.POST)
    cf.save(commit=False)
    cf.feeder = funddetail.feeder
    cf.save()