当创建一个拥有布尔类型字段my_boolean_field
且默认值设置为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)