2012-12-17 73 views
1

我想使總計從其他兩個領域的計算字段,但不知道如何分別獲得他們的數據。 (我試過.value的,沒有任何的喜悅)Django:如何計算來自其他兩個字段的字段的初始值?

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'].??? 

回答

2

假設你正在處理一個綁定的形式,你可以使用**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

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)) 
相關問題