简体   繁体   English

如何更改表单 CharField 中的默认空代表?

[英]How to change default empty representative in forms CharField?

I use an unbound form with BooleanField and CharField我使用带有 BooleanField 和 CharField 的未绑定表单

None are required不需要

but when empty, value in database is a representative empty string for Charfield and 0 for BooleanField但是当为空时,数据库中的值是 Charfield 的代表空字符串和 BooleanField 的 0

I would like NULL value instead but don't find how to set this.我想要 NULL 值,但没有找到如何设置它。

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.如果要将空值设置为 null,只需在字段中添加 null=True 即可。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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