简体   繁体   中英

How to change default empty representative in forms CharField?

I use an unbound form with BooleanField and CharField

None are required

but when empty, value in database is a representative empty string for Charfield and 0 for BooleanField

I would like NULL value instead but don't find how to set this.

class CreateForm(forms.Form):

    def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(*args, **kwargs)
        self.fields["field1"] = forms.BooleanField(label = "", required = False, initial=None)
        self.fields["field2"] = forms.CharField(label = "", required = False, initial=None)

If you want to set empty values as null you can just add null=True to your field.

class CreateForm(forms.Form):

    def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(*args, **kwargs)
        self.fields["field1"] = forms.BooleanField(label = "", required = False, initial=None, null=True)
        self.fields["field2"] = forms.CharField(label = "", required = False, initial=None, null=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM