Django自定义验证器不起作用

时间:2016-04-14 07:54:01

标签: django python-2.7 django-models django-validation

我编写了一个自定义验证器,如果给定的字段值为负,则会引发ValidationError。

  def validate_positive(value):
        if value < 0:
            raise ValidationError(
                    _('%(value) is negative number'),
                    params = {'value': value}
                    )

我通过字段的验证器参数

将其添加到我的模型字段中
class Book(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    price = models.IntegerField(default=0,validators=[validate_positive])
    quantity = models.IntegerField(default=0,validators=[validate_positive])

但是在创建对象时,如果价格小于零,它不会引发任何错误 我不知道我做错了什么,我是django的新手。
我正在使用 Django 1.9 请帮帮我。

2 个答案:

答案 0 :(得分:5)

验证器用于表单,而不是用于创建对象。如果您要在表单之外创建对象,则需要提供另一种验证输入的方法。

最简单的方法是在保存前调用模型的full_clean方法,如docs

所示
from django.core.exceptions import ValidationError
try:
    article.full_clean()
except ValidationError as e:
    # Do something based on the errors contained in e.message_dict.
    # Display them to a user, or handle them programmatically.
    pass

这类似于表单中发生的情况,并会调用模型字段上的任何验证器。

答案 1 :(得分:0)

我遇到了同样的问题。因此,验证器仅在您使用 Forms 和 Model Form 填写时才起作用。

不过,您可以在 shell 中验证验证器。

python manage.py shell
>>>from app.models import Book
>>>Book.price.field.run_validators(value=<undesirable value>)

这会引发验证错误,因此您可以确保验证有效。