Welyweloo
Welyweloo

Reputation: 98

Models CharField Blank and Null

I have the following model :

class Scenario(models.Model):
    title = models.CharField(max_length=30)
    subtitle = models.CharField(max_length=60)
    description = models.TextField(max_length=1000)
    image_url = models.ImageField(upload_to ='scenarios-pictures/%Y/%m/%d', default="", blank=False, null=False)
    slug = models.SlugField(null=True, unique=True)
    active = models.BooleanField(default=False)

    def __str__(self):
        return self.title

If I try to create a scenario with empty values, it doesn't raise any exception.

>>> from ihm_maquette.models import Scenario
>>> scenario = Scenario.objects.create(title='', subtitle='', description='', image_url='', slug='')
>>> scenario
<Scenario: >
>>> 

I don't get why, because I've read in the doc that blank and null are False by default. I've also read this explanation.

Do you have any idea why the object is created?

Upvotes: 0

Views: 691

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21787

null=False does not mean a CharField cannot have an empty string as a value. Also the model's create and save, etc. methods do not validate the model while creating it. The blank attribute is used when the model is validated, usually the form will call the various methods on the model available for validating the instance when you call form.is_valid(). You can validate an instance by simply calling the full_clean method (Reference Validating objects [Django docs]):

from ihm_maquette.models import Scenario


# Don't call create instantiate it first
scenario = Scenario(title='', subtitle='', description='', image_url='', slug='')
scenario.full_clean() # will raise exception here
scenario.save()

Upvotes: 1

Related Questions