Consider the following model field:
myfield = models.IntegerField(_('My field'), blank=True, default=0)
If the myfield is completely omited from the post the default is properly used by default ModelForm implementation. However if empty string is posted for that field the field value stays None and postgres fails with the IntegrityError on non-null field:
IntegrityError: null value in column "myfield" violates not-null constraint
Question: How to enforce a default for both cases where either the myfield value is not present or present but empty string?
What makes me think this is a django bug is ModelForm validation passes successfully but yet it fails to save the form. Although semantically field declaration is correct, and if empty string is not a valid value for a field the form validation should fail otherwise should ensure the field value gets assigned a proper integer.
Implementing a clean method to replace empty strings with default value is possible but quite ugly. Looking for a better way to do this:
This is apparently expected behaviour, and a reference to it is make on this wiki page.
default is the default value to use for a field when creating new objects and no value of any sort is specified for the field. It is not used to populate a field when an empty value is passed in a form.
blank specifies whether an empty value is allowed in forms. But it doesn't control whether that empty value is valid in the database.
As a result default will not do what you want here, and when you pass an empty string in the form this will get passed to the database as a null value.
You have two options:
Set null=True on the field to allow null values (but this might not make sense semantically).
Override the clean method on the model to convert null values to 0 before they are saved, e.g.:
def clean(self):
if self.myfield is None:
self.myfield = 0
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