Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

When creating an instance of a model having a BooleanField my_boolean_field with a default set to True, I get an error:

my_boolean_field is required

Shouldn't it be set to the default value?

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)
share|improve this question

1 Answer

up vote 0 down vote accepted

Change field definition in your model form to specify require=False.

class MyModelCreationForm(UserCreationForm):   

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

    class Meta:
        model = User

Note on 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.

share|improve this answer
Ok, I thought that if the user didn't set it, it would be set to the default value. – jul Jun 6 at 6:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.