gpt4 book ai didi

django - 创建模型实例时未设置BooleanField默认值

转载 作者:行者123 更新时间:2023-12-02 09:20:29 24 4
gpt4 key购买 nike

当创建一个具有 BooleanField my_boolean_fielddefault 设置为 True 的模型实例时,我得到一个错误:

my_boolean_field is required

不应该设置为默认值吗?

models.py

class MyModel(User):

my_boolean_field = models.BooleanField(default=False)

admin.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)

最佳答案

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

class MyModelCreationForm(UserCreationForm):   

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

class Meta:
model = User

关于BooleanField reference的注释

Note Since all Field subclasses have required=True by default, the validation condition here is important. If you want to include a boolean in your form that can be either True or False (e.g. a checked or unchecked checkbox), you must remember to pass in required=False when creating the BooleanField.

关于django - 创建模型实例时未设置BooleanField默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16955256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com