2014-11-06 127 views
0

我想添加一個自定義的驗證作爲我的窗體的一部分。Django - 自定義驗證錯誤

我試圖在voluntary_date_display_type是指定的數字時跳過自定義驗證。但是,當我運行以下代碼時,voluntary_date_display_type值爲,我期待的是數字/數字。

我已閱讀form field validation上的django文檔,但我看不到我的錯誤。

當前只有最後的else條件被觸發,因爲該值爲None。

有人能指出我做錯了什麼嗎?

這裏是我的forms.py文件中的代碼:

class Meta: 
    model = VoluntaryDetails 

    fields = (
     ....... 
     'voluntary_date_display_type', 
     ....... 
    ) 

def clean_voluntary_finish_date(self): 

    voluntary_display_type = self.cleaned_data.get('voluntary_display_type') 
    voluntary_start_date = self.cleaned_data.get('voluntary_start_date') 
    voluntary_finish_date = self.cleaned_data.get('voluntary_finish_date') 
    voluntary_date_display_type = self.cleaned_data.get('voluntary_date_display_type') 

    if voluntary_display_type == 0: 
     if voluntary_finish_date is not None and voluntary_start_date is not None: 
      if voluntary_start_date > voluntary_finish_date: 
       if voluntary_date_display_type == 2 or voluntary_date_display_type == 3: 
        raise forms.ValidationError(_("To Date must be after the From Date.")) 
       elif voluntary_date_display_type == 4 or voluntary_date_display_type == 5: 
        raise forms.ValidationError(_("Finish Date must be after the Start Date.")) 
       elif voluntary_date_display_type == 6 or voluntary_date_display_type == 7: 
        raise forms.ValidationError(_("End Date must be after the Begin Date.")) 
       elif voluntary_date_display_type == 8: 
        raise forms.ValidationError(_("This Date must be after the other Date.")) 
       elif voluntary_date_display_type == 9 or voluntary_date_display_type == 10: 
        raise forms.ValidationError(_("This Duration date must be after the other Duration date.")) 
       else: 
        raise forms.ValidationError(_("Completion Date must be after the Commencement Date.")) 

    return voluntary_finish_date 

回答

1

clean_voluntary_finish_date當該特定域的驗證才調用,所以其他人可能還沒有被「清洗」。這意味着當您使用self.cleaned_data.get('voluntary_date_display_type')時,該字段尚未清除,因此cleaned_data中沒有密鑰,並且.get()方法將返回None

當驗證取決於多個字段時,您需要使用正常的clean()方法;在Django的規定形成reference「是互相依賴的清潔和驗證領域」:

假設我們加入到我們的聯繫表格另一個要求:如果 cc_myself場爲True,主體必須包含單詞「幫助」。我們 一次對多個字段進行驗證,所以表單的clean()方法是一個很好的選擇。 請注意,我們是 在這裏討論表單上的clean()方法,而之前我們 在字段上寫了一個clean()方法。在確定何處驗證 的事情時,務必保持 字段和表格差異的清晰。字段是單個數據點,表單是 字段的集合。

通過被稱爲形式的清潔()方法中,所有的個體 場清潔方法將已經運行(前兩節)的時候,所以 self.cleaned_data將與已存活,因此任何數據填充 遠。因此,您還需要記住允許您想要驗證的 字段可能沒有在最初的 單個字段檢查中存活。

所有你需要做的是:

def clean(self): 
    cleaned_data = super(YourFormClassName, self).clean() 
    # copy and paste the rest of your code here 
    return cleaned_data # this is not required as of django 1.7