在Django模型格式中覆盖Clean方法时,禁用了基本验证 [英] Basic validation disabled when overriding clean method in Django modelforms

查看:61
本文介绍了在Django模型格式中覆盖Clean方法时,禁用了基本验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一次又一次地阅读Django文档,但是我一直在挣扎于modelforms中的clean()方法。

I read the Django doc again and again but I keep struggling with the clean() method in modelforms.

这是我的models.py:

Here is my models.py:

class Profile(models.Model):

    number1 = models.IntegerField(blank=True, null=True)
    number2 = models.IntegerField(blank=True, null=True)

class FormProfile(ModelForm):

    def clean(self):

        number1 = self.cleaned_data.get('number1')
        number2 = self.cleaned_data.get('number2')

        if number1 >= number2:

            raise forms.ValidationError("number1 should not be above number2")

    class Meta:

        model = Profile

clean()验证正确完成,但是问题是number1和number2的基本验证(应该为整数)不会引发任何问题错误了。
例如,如果number1是整数,但number2不是整数,则cleaned_data字典将仅包含number1,这是正常的,因为number2没有经过验证,但不会引发错误。

The clean() validation is done properly, but problem is that the basic validation of number1 and number2, which should be integers, does not raise any error anymore. For instance, if number1 is an integer but number2 is not an integer, then the cleaned_data dictionnary will only contain number1, which is normal since number2 was not validated, but no error is raised.

我如何才能使Django先引发基本错误,然后仅在未引发基本错误的情况下执行clean()方法?

How can I make Django raise the basic errors first and then perform the clean() method only if no basic error is raised ?

谢谢!

推荐答案

您正在谈论的基本验证通过 BaseForm clean 方法,当您覆盖此方法时,您将隐藏基础验证。

The basic validation you're talking about is invoked via the BaseForm's clean method, when you overrode this method, you hid the underlying validation.

您需要在清洁方法中通过super调用ModelForms基本清洁方法

You need to call the ModelForms base clean method via super in your clean method

   def clean(self):
       super(FormProfile, self).clean()

如< a href = https://docs.djangoproject.com/zh-CN/1.9/ref/forms/validation/#validating-fields-with-clean rel = nofollow>文档,您仍然需要检查如果您的支票中没有值,那么如果number1和number2和number1> = number2:$ b,它将变成

As shown in the example in the docs, you will still need to check if a value is none in your check so it would become

 if number1 and number2 and number1 >= number2:

您可以在 .get 中提供默认值,但是我不会建议不要这样做,因为这会使检查更难验证正确结果

You could provide a default value with .get but I wouldn't recommend it as it would make this check a little harder to verify correct results

这篇关于在Django模型格式中覆盖Clean方法时,禁用了基本验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆