Django BooleanField as radio buttons?
Solution 1:
Django 1.2 has added the "widgets" Meta option for modelforms:
In your models.py, specify the "choices" for your boolean field:
BOOL_CHOICES = ((True, 'Yes'), (False, 'No'))
class MyModel(models.Model):
yes_or_no = models.BooleanField(choices=BOOL_CHOICES)
Then, in your forms.py, specify the RadioSelect widget for that field:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
widgets = {
'yes_or_no': forms.RadioSelect
}
I've tested this with a SQLite db, which also stores booleans as 1/0 values, and it seems to work fine without a custom coerce function.
Solution 2:
You could do this by overriding the field definition in the ModelForm:
class MyModelForm(forms.ModelForm):
boolfield = forms.TypedChoiceField(
coerce=lambda x: x == 'True',
choices=((False, 'False'), (True, 'True')),
widget=forms.RadioSelect
)
class Meta:
model = MyModel