Django:验证程序返回False,但form.is_valid()== True

时间:2018-07-09 10:43:17

标签: django python-3.x django-models django-forms django-2.0

我创建了一个自定义验证器,用于检查RangeField中的大写数字是否小于某个数字。

问题是我可以在调试模式下看到Validator.compare返回False,但是Django上升了DataError

  

值“ 21474834555”超出整数类型LINE 1的范围:... NULL,   “ cena” = NULL,“ poznamka” =“,” rozloha“ ='[-214748 ...

我不知道为什么它应该在此之前引发ValidationError时引发此错误。

我知道数字超出范围,这就是为什么我创建了Validator的原因。

查看

class DopytUpdateView(LoginRequiredMaklerAccessMixin, UpdateView):
    model = Dopyt
    form_class = DopytForm
    template_name = 'dopyty/dopyt.html'

表格

class DopytForm(forms.ModelForm):

    class Meta:
        model = Dopyt
        fields = [...'rozloha',...]

验证器

class RangeCompleteMaxValueValidator(MaxValueValidator):
    def compare(self, a, b):
        upper_ok = (a.upper > b) if a.upper else True
        lower_ok = (a.lower > b) if a.lower else True
        return upper_ok and lower_ok

模型

class Dopyt(TimeStampedModel):
    ...
    rozloha = IntegerRangeField(null=True, blank=True, verbose_name='Rozloha [m2]',
                                validators=[RangeCompleteMinValueValidator(-2147483648),
                                            RangeCompleteMaxValueValidator(2147483647)])

你知道为什么会这样吗?

编辑

如您所见,验证器返回False

enter image description here

1 个答案:

答案 0 :(得分:0)

表单验证器看不到模型验证器,如果要避免到达模型层,则必须使用clean

您的validador在您的模型实例上运行,因此当您保存...时,form.is_valid在窗体中运行,因此此验证不会到达您的模型...要在您的窗体上验证逻辑,应使用clean

from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject:
            # Only do something if both fields are valid so far.
            if "help" not in subject:
                raise forms.ValidationError(
                    "Did not send for 'help' in the subject despite "
                    "CC'ing yourself."
                )

https://docs.djangoproject.com/en/2.0/ref/forms/validation/