If I try to save incomplete model instance in Django 1.10, I would expect Django to raise an error. It does not seem to be the case.
models.py:
from django.db import modelsclass Essai(models.Model):ch1 = models.CharField(max_length=100, blank=False)ch2 = models.CharField(max_length=100, blank=False)
So I have two fields not allowed to be empty (default behavior, NOT NULL
restriction is applied by Django at MySQL table creation). I expect Django to rase an error if one of the fields is not set before storing.
However, when I create an incomplete instance, the data is stored just fine:
>>> from test.models import Essai
>>> bouh = Essai()
>>> bouh.ch1 = "some content for ch1"
>>> bouh.save()
>>> bouh.id
9
>>> bouh.ch1
'some content for ch1'
>>> bouh.ch2
''
>>>
I would have expected Django to raise an error. If I force ch2
to None
, however, it raises an error:
>>> bouh = Essai()
>>> bouh.ch1 = "some content for ch1"
>>> bouh.ch2 = None
>>> bouh.save()
Traceback (most recent call last):(...)return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: test_essai.ch2
>>> bouh.id
>>> bouh.ch1
'some content for ch1'
>>> bouh.ch2
>>>
Is this normal behavior? Did I miss something? Why is Django not raising an error as default behavior in this simple case?
Thanks for your lights!
EDIT
I got a few replies pointing out the fact that in SQL empty string ""
is not equivalent to NULL, as stated in Django model blank=False does not work?
However, if we look at ModelForm behavior, there seem to be a inconsistency in django doc.
see question Followup : missing required Charfield in django Modelform is saved as empty string and do not raise an error