2014-11-06 126 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