I find that when I insert nothing of a string form field
through a form it captures it as an empty string ''
.
However when I insert nothing of an integer form field
through a form it captures it as [null]
.
Is this good practice? Should the string be null
as well in the db?
null is purely database-related, whereas blank is validation-related(required in form). If null=True , Django will store empty values as NULL in the database . If a field has blank=True , form validation will allow entry of an empty value . If a field has blank=False, the field will be required.
null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database.
If a string-based field has null=True , that means it has two possible values for “no data”: NULL , and the empty string. In most cases, it's redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL .
If your foreign key field can take null values, it will return None on null, so to check if it was "left blank", you could simply check if the field is None .
It depends on the field.empty_strings_allowed
attribute.
Some fields have it overridden to False
. But CharField
keeps it True
, thus making Field._get_default return empty string as default — even if blank=True
. The only way to get None
as default is to have null=True
on a field.
So if you have field in db that should never be null and not allow blanks to be never ever put in there by for e.g. objects.create
. You need to put self.full_clean()
— or other validation — in the model save
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With