If have the following Django (1.4) model:
from django.db import models
class SimpleModel(models.Model):
name = models.CharField(max_length=100)
And this simple test:
from django.test import TestCase
from models import SimpleModel
from django.db import IntegrityError
class SimpleTest(TestCase):
def test_integrity_error(self):
with self.assertRaises(IntegrityError):
m = SimpleModel()
m.save()
As database a sqlite3 database is used. If I now run the tests with python manage.py test <appname> the test fails with AssertionError: IntegrityError not raised.
The question is: why?
As far as I understand (or thought to understand) Django the default values for Fields are blank=False and null=False so I would assume that saving an model instance with the default value (which I think for a CharField should be an empty string) should certainly fail! So, why doesn’t this happen?
Django never stores NULL for empty
CharFieldorTextFieldtypes. It stores an empty string (''). So that’s why you don’t get anIntegrityErrorfornull=False.As for
blank=False, that only affects forms. It just makes the form set the field asrequired=Trueso it won’t validate unless it has a value. It doesn’t affect the database or your ability to manually set a blank value outside of a form.