Chad
Chad

Reputation: 1818

Django ModelForm won't allow Null value for required field?

I have a Model with this field...

fulfillment_flag = models.CharField(pgettext_lazy('Delivery group field', 'Fulfillment Flag'), max_length=255,
                                        null=True, choices=FULFILLMENT_FLAG_CHOICES)

And here is my form...

class FulfillmentFlagForm(forms.ModelForm):

    class Meta:
        model = DeliveryGroup
        fields = ['fulfillment_flag', ]

    def clean_fulfillment_flag(self):
        return self.cleaned_data['fulfillment_flag'] or None

I have an HTML select drop down that has a blank value option at the top. Every time I select the blank option and click Save, form will not save it as a Null value on my model. It'll save any of the other fields though, just not the blank one. And it will tell me that the field is required as well.

How can I tell the form to just save the blank value as Null?

Upvotes: 5

Views: 8406

Answers (1)

Christine Schäpers
Christine Schäpers

Reputation: 1318

https://docs.djangoproject.com/en/1.8/ref/models/fields/#null

Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. 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.

For both string-based and non-string-based fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).

Do blank=True instead and save "" instead of None.

Upvotes: 7

Related Questions