简体   繁体   中英

Django model phone field

The contents of models.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.

Now, here is what I tried in the 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)?

I checked the table books_author and that row got added.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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