2

我想将总计作为其他两个字段的计算字段,但不确定如何分别获取它们的数据。(我尝试了 .value 没有任何喜悦)

Class TestForm(ModelForm):

    def __init__(self, *args, **kwargs):
       super(TestForm, self).__init__(*args, **kwargs)        
       self.fields['total_price'].initial = self.fields['price'].??? * self.fields['quantity'].???
4

2 回答 2

3

假设您正在处理绑定表单,您可以使用它**kwargs['instance']来获取模型实例。

因此,您的__init__方法将类似于-

  def __init__(self, *args, **kwargs):
       super(TestForm, self).__init__(*args, **kwargs)  
       instance = kwargs['instance']
       self.fields['total_price'].initial = instance.price * instance.quantity

如果您不处理绑定表单,那么您可以使用self.fields['price'].initial

于 2012-12-17T17:43:28.627 回答
0

您也是在视图中执行此操作的一种选择.....

老式的方式....

但这不是模型形式...

所以艾丹的回答更好,但如果你真的想做定制的东西......老式的方式

if request.method == 'POST': # If the form has been submitted...
    form = TestForm(request.POST) # A form bound to the POST data
    if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            whatever = form.cleaned_data['whatever']
            #and you can update the data and make the form with the new data
            data = {'whatever': whatever,'etc.': etc}
            form=TestForm(data)

else:
    # An unbound form
    form = TestForm(initial={'whatever': whatever,'etc.': etc})
return render_to_response(template,{'form':forms},context_instance=RequestContext(request))
于 2012-12-17T18:20:38.990 回答