我想将总计作为来自其他两个字段的计算字段,但不确定如何分别获取其数据。 (我没有任何快乐地试过.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'].???
答案 0 :(得分:2)
假设您正在处理绑定表单,可以使用**kwargs['instance']
来获取Model实例。
所以你的__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
答案 1 :(得分:0)
你也可以在意见中做到这一点......
老式的方式....
但那不是模特形式......
所以Aidan的答案更好,但如果你真的想做自定义的东西......老式的方式
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))