Model Validation

By default, Django does not use Model Validation (unless we use ModelForm). Please see the end of Chapter 7 in the book for more details.


In [1]:
from datetime import date
from blog.models import Post

In [2]:
"""
# If the command below does not work, remove the triple-quotation lines and run again
training_post = Post.objects.create(
    title='Django Training',
    slug='django-training',
    text=(
        "Learn Django in a classroom setting "
        "with JamBon Software."),
)
training_post.pub_date = date(2013, 1, 18)
training_post.save()
"""
training_post = Post.objects.get(slug='django-training')
training_post


Out[2]:
<Post: Django Training on 2013-01-18>

In [3]:
conflict = Post.objects.create(
    title='Conflict',
    slug=training_post.slug,  # Our Post model defines slug as unique!
    pub_date=training_post.pub_date,
    text='This object will cause problems.',
)
conflict


Out[3]:
<Post: Conflict on 2015-06-09>

In [4]:
# auto_now_add=True has overriden our pub_date
# we therefore reset the date again
conflict.pub_date = training_post.pub_date
conflict.save()
conflict


Out[4]:
<Post: Conflict on 2013-01-18>

In [5]:
Post.objects.all()


Out[5]:
[<Post: Conflict on 2013-01-18>, <Post: Django Training on 2013-01-18>]

In [6]:
# this exception will be displayed at http://127.0.0.1:8000/blog/2013/11/django-training/
try:
    Post.objects.get(
        pub_date__year=2013,
        pub_date__month=1,
        slug='django-training'
    )
except Post.MultipleObjectsReturned as e:
    print(str(e))


get() returned more than one Post -- it returned 2!

In [7]:
conflict2 = Post(
    title='Conflict 2: The Return',
    slug=training_post.slug,
    text='More Problem Behavior in Theaters Soon!',
)
conflict2.save()
conflict2.pub_date = training_post.pub_date
conflict2.save()
conflict2


Out[7]:
<Post: Conflict 2: The Return on 2013-01-18>

In [8]:
# this exception will be displayed at http://127.0.0.1:8000/blog/2013/11/django-training/
try:
    Post.objects.get(
        pub_date__year=2013,
        pub_date__month=1,
        slug='django-training'
    )
except Post.MultipleObjectsReturned as e:
    print(str(e))


get() returned more than one Post -- it returned 3!

In [9]:
from django.core.exceptions import ValidationError
try:
    conflict.full_clean()
except ValidationError as e:
    print(str(e))


{'slug': ['Slug must be unique for Date published month.']}

In [10]:
Post.objects.all()


Out[10]:
[<Post: Conflict on 2013-01-18>, <Post: Conflict 2: The Return on 2013-01-18>, <Post: Django Training on 2013-01-18>]

In [11]:
Post.objects.filter(title__icontains='conflict').delete()
Post.objects.all()


Out[11]:
[<Post: Django Training on 2013-01-18>]