1

图书应用程序的 models.py 的内容。

from django.db import models
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator


class Author(models.Model):
    name = models.CharField(max_length=30, unique=True)
    email = models.EmailField(max_length=50)
    phone = models.IntegerField(max_length=10, unique=True, validators=[RegexValidator(regex='^\d{10}$', message='Length has to be 10', code='Invalid number')])
    # phone = models.IntegerField(max_length=10)

    def __unicode__(self):
        return self.name

在 Author 类中,我希望电话号码仅接受长度为 10 的数字。如果 IntegerField 具有 min_length 属性,我将使用它。

现在,这是我在 django shell 中尝试过的

>>> from books.models import *
>>> p = Author(name='foo', email='foo@bar.com', phone='962027')
>>> p.save()
>>>

为此,它不应该引发错误,说明电话字段无效(因为它没有 10 位数字)?

我检查了表 books_author 并添加了该行。

我在这里做错了什么?请帮忙。

4

1 回答 1

4

请参阅有关如何运行验证器的文档,特别是:

请注意,保存模型时验证器不会自动运行

您需要使用表单进行验证,或p.full_clean()显式调用。

于 2013-08-30T10:15:02.367 回答