Python/Django BooleanField model with RadioSelect form default to empty

Joe J picture Joe J · Aug 12, 2010 · Viewed 9.8k times · Source

I'm using a Django ModelForm where my model contains a BooleanField and the form widget associated with that BooleanField is a RadioSelect widget. I'd like the the RadioSelect widget that renders to have no options selected so the user has to explicitly make a choice, but the form validation to fail if they make no selection. Is there a way to do this?

models.py

myboolean = models.BooleanField(choices=YES_NO)

forms.py

class myModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(myModelForm, self).__init__(*args, **kwargs)
        self.fields['myboolean'].widget = forms.RadioSelect(choices=YES_NO)

Answer

Andrey Fedoseev picture Andrey Fedoseev · Aug 12, 2010

Your code actually does what you need. It renders the radio buttons with no options selected and generate the error message if nothing is selected.

A small note about your form code. I would do it like this:

class myModelForm(forms.ModelForm):

    myboolean = forms.BooleanField(widget=forms.RadioSelect(choices=YES_NO))

    class Meta:
        model = MyModel