覆盖django中的默认验证器

时间:2015-02-13 19:40:31

标签: python django validation

给出模型字段

my_number = models.PositiveIntegerField(validators=[ MaxValueValidator(360) ])

有没有办法覆盖最小和最大默认验证器?上面我只是添加一个新的验证器,它在服务器上运行良好。但是,我将验证器字典传回客户端,并在字段上设置了两个MaxValueValidators而不是一个。{}

1 个答案:

答案 0 :(得分:0)

您是否考虑过覆盖表单的clean()函数?

作为一个例子,这是我过去做过的事情:

class ChemLabTimeSelect(forms.Form):

    from_date = forms.DateTimeField(
        widget=DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss",
                                       "pickTime": True}))
    to_date = forms.DateTimeField(
        widget=DateTimePicker(options={"format": "YYYY-MM-DD HH:mm:ss",
                                       "pickTime": True}))

    def clean(self):
        cleaned_data = self.cleaned_data
        if cleaned_data.has_key('from_date') and cleaned_data.has_key('to_date'):
            total_days = (cleaned_data['to_date'] - cleaned_data['from_date']).days 
            negative_days = (cleaned_data['from_date'] - cleaned_data['to_date']).total_seconds() 
            if negative_days > 0:
                raise ValidationError({'from_date':["The from date is greater than the to date!",]})
            elif total_days > 7:
                raise ValidationError(["The amount of time selected is %s days which is too large!" % total_days,])          
        return cleaned_data

此外,该模型还具有clean()覆盖功能,并且应该能够实现所需的结果。但是应该意识到形式和模型的干净覆盖之间的差异。