2010-02-21 46 views
12

我是Django(和Python)的新手,並試圖弄清楚如何對錶單驗證的某些方面進行條件化。在這種情況下,應用程序有一個HTML接口,用戶可以從小部件中選擇日期和時間。表單對象上的clean方法獲取時間和日期字段的值,並將其重新轉換爲datetimeDjango表單驗證:使「必需」條件?

除了HTML界面,這裏還有一個iPhone客戶端撥打電話到應用程序,我想在傳遞一個UNIX時間戳式時間值

我的表單代碼如下所示:

class FooForm(forms.ModelForm): 
    foo_date    = forms.CharField(required=True, widget=forms.RadioSelect(choices=DATE_CHOICES)) 
    foo_time    = forms.CharField(required=True, widget=SelectTimeWidget()) 
    foo_timestamp  = forms.CharField(required=False) 

我如何foo_datefoo_time需要除非foo_timestamp提供?

回答

21

這是通過表單上的clean方法完成的。不過,您需要將foo_datefoo_time設置爲required=False,因爲clean僅在每個字段都經過驗證後纔會調用(另請參閱documentation)。

class FooForm(forms.Form) 
    # your field definitions 

    def clean(self): 
     data = self.cleaned_data 
     if data.get('foo_timestamp', None) or (data.get('foo_date', None) and data.get('foo_time', None)): 
      return data 
     else: 
      raise forms.ValidationError('Provide either a date and time or a timestamp') 
+0

謝謝,我在想'乾淨'可能是這樣做的地方。但是,是否有可能針對'foo_date'和'foo_time'字段驗證錯誤,而不是一般的表單驗證錯誤? 謝謝,克里斯 – ChrisW 2010-02-21 19:49:08

+1

這在第二個例子中解釋我鏈接到 – 2010-02-21 19:59:22

+0

self.RTFM的文檔;謝謝,我會深入挖掘。 – ChrisW 2010-02-21 20:12:45

8

我發現自己需要一個「標準」方式來做到這一點,因爲我的表單有幾個有條件的必填字段。所以,我創建了以下方法用超:

def validate_required_field(self, cleaned_data, field_name, message="This field is required"): 
    if(field_name in cleaned_data and cleaned_data[field_name] is None): 
     self._errors[field_name] = self.error_class([message]) 
     del cleaned_data[field_name] 

然後在我的表格的清潔方法,我有:

def clean(self): 
    cleaned_data = super(FormClass, self).clean() 
    if(condition): 
     self.validate_required_field(cleaned_data, 'field_name') 

它至今完全爲我工作。