简体   繁体   English

Django模型电话领域

[英]Django model phone field

The contents of models.py for books app. books.py for books app的内容。

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

Here in the Author class, I want the phone numbers to accept only digits with length 10. I would have used an IntegerField if it had a min_length attribute. 在Author类中,我希望电话号码只接受长度为10的数字。如果它具有min_length属性,我会使用IntegerField。

Now, here is what I tried in the django shell 现在,这是我在django shell中尝试的内容

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

For this, shouldn't it raise an error saying the phone field is not valid(since it does not have 10 digits)? 为此,它不应该引发一个错误,说电话字段无效(因为它没有10位数)?

I checked the table books_author and that row got added. 我查看了books_author表,并添加了该行。

What did I do wrong here? 我在这做错了什么? Please help. 请帮忙。

See the documentation about how validators are run , in particular: 请参阅有关验证程序如何运行的文档,特别是:

Note that validators will not be run automatically when you save a model 请注意,保存模型时,验证程序不会自动运行

You need to validate using a form, or call p.full_clean() explicitly. 您需要使用表单进行验证,或者显式调用p.full_clean()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM