4

在创建具有设置为的模型的实例时,BooleanField my_boolean_field出现default错误True

my_boolean_field is required

不应该设置为默认值吗?

模型.py

class MyModel(User):

    my_boolean_field = models.BooleanField(default=False)

管理员.py

class MyModelCreationForm(UserCreationForm):   

    my_boolean_field = forms.BooleanField(initial=False)

    class Meta:
        model = User

class MyModelChangeForm(UserChangeForm):

    my_boolean_field = forms.BooleanField(initial=False)

    class Meta:
        model = User


class MyModelAdmin(UserAdmin):

    form = MyModelChangeForm
    add_form = MyModelCreationForm

    list_filter = ()
    list_display = ('username', 'my_boolean_field')

    fieldsets = (
        (None, {'fields': ('username', 'my_boolean_field', 'password' )}),
    )


    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'my_boolean_field', 'password1', 'password2')}
        ),
    )

    def get_form(self, request, obj=None, **kwargs):
        form = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
        if obj==None:
            form.base_fields['username'].widget.attrs['autocomplete'] = 'off'
            form.base_fields['password1'].widget.attrs['autocomplete'] = 'off'
            form.base_fields['password2'].widget.attrs['autocomplete'] = 'off'
        return form

samsic_site.register(MyModel, MyModelAdmin)
4

1 回答 1

5

更改模型表单中的字段定义以指定require=False.

class MyModelCreationForm(UserCreationForm):   

    my_boolean_field = forms.BooleanField(initial=False, required=False)

    class Meta:
        model = User

参考说明BooleanField

注意 由于所有的 Field 子类默认都有 required=True ,所以这里的验证条件很重要。如果您想在表单中包含一个可以为 True 或 False 的布尔值(例如选中或未选中的复选框),您必须记住在创建 BooleanField 时传入 required=False。

于 2013-06-06T06:44:23.283 回答