Blankable, non-nullable CharFields have a strange default behavior
|Reported by:||Owned by:||nobody|
|Cc:||brosner@…, paul@…||Triage Stage:||Accepted|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
If you create a create a CharField in a model like so:
some_field = models.CharField(blank=True, null=False)
then create the database via syncdb, the model/validation layer considers None to be a valid value even though it just created the database table with NOT NULL as an attribute for the some_field column. This leads to some trouble. For starters, if you neglect to include some_field in a form, the field will not produce any POST data, but the lack of a value won't trigger a model validation error. This is made worse by the fact that Fields seem to default their default values to None. Defaulting to None will always produce database errors here unless you somehow go behind Django's back and modify the database to allow NULL values while keeping null for the field equal to False. Thus, an invalid insertion will be sent to the database, causing a nasty exception...
Since the preferred method for storing blank values in CharFields is to use an empty string, I feel this should really be handled by default differently. Some ideas:
- For CharField, blank=True when used together with null=False could imply, unless otherwise specified, that the default value is an empty string (The documentation already says that empty strings are the preferred method of storing blank values in a CharField, so why is it defaulting to a bad value?)
- When null=True for a field, Field.validate could raise an exception and warn when asked to validate None, since it is not, after all, a valid value for a field where NULL is not allowed.
Change History (5)
comment:1 Changed 10 years ago by
|Patch needs improvement:||unset|
|Triage Stage:||Unreviewed → Accepted|