2013-07-04 47 views
1

我有一個窗體,只有在選擇單選按鈕時才需要一些字段。如何使一些Django表單域取決於其他字段的值?

如果我將該字段設置爲「required = True」,那麼它的行爲就是所希望的,但是當未選中單選按鈕時,如何讓它表現爲「required = False」?

我想我會去的required=False默認然後檢查單選按鈕的值form.clean(),並呼籲爲clean_<field>對於那些現在需要的字段,但它似乎並沒有那麼簡單。或者是?

另外,我會從required=True開始,然後在form.clean()檢查單選按鈕的值,如果沒有設置,那麼只是刪除從不再需要的字段引發的任何錯誤?

回答

0

form.clean是正確的做法。不正確的是在其他字段中調用clean_<field> - 它們已經被清理,其值將在cleaned_data字典中。

看一看在文檔的例子: https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other 它貫穿幾乎完全此方案中,展示瞭如何可以基於另一個測試一個領域,以及如何丟失時,您可以提高窗體級錯誤或綁定錯誤的領域之一。

2

哦,看起來,我所做的一切都是靠我的寂寞......後一種選擇確實比在特定領域找到並調用驗證例程簡單得多。更容易壓扁的錯誤:

設置所有可能需要的領域required=True然後在form.clean()測試其他字段的值,如果有必要,只是從self.errors

# payment type 
payment_method = forms.CharField(max_length="20", required=True) 
payment_method.widget=forms.RadioSelect(choices=PAYMENT_METHOD_CHOICES) 

# credit card details 
cc_number = CreditCardField(max_length=20, required=True) 
cc_name = forms.CharField(max_length=30, required=True) 
cc_expiry = ExpiryDateField(required=True) 
cc_ccv = VerificationValueField(required=True) 

def clean(self): 
    data = super(PaymentForm, self).clean() 
    if data.get('payment_method') == 'paypal': 
     for field_name in ['cc_number','cc_name','cc_expiry','cc_ccv']: 
      if field_name in self.errors: 
       del self.errors[field_name] 
刪除錯誤
相關問題