Reputation: 304
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='[email protected]', 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.
Upvotes: 1
Views: 8268
Reputation: 599856
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.
Upvotes: 4