Django BooleanField as radio buttons?

Viewed 45900

Is there a widget in Django 1.0.2 to render a models.BooleanField as two radio buttons instead of a checkbox?

11 Answers

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

Also remember that MySQL uses tinyint for Boolean, so True/False are actually 1/0. I used this coerce function:

def boolean_coerce(value):
    # value is received as a unicode string
    if str(value).lower() in ( '1', 'true' ):
        return True
    elif str(value).lower() in ( '0', 'false' ):
        return False
    return None

update for django version 3.0:

BOOLEAN_CHOICES = (('1', 'True label'), ('0', 'False label'))
  # Filtering fields
    True_or_false_question = forms.ChoiceField(
        label="Some Label3",
  # uses items in BOOLEAN_CHOICES
        choices = BOOLEAN_CHOICES,
        widget = forms.RadioSelect
    )

it gives a bullet point button list, i dont know how to make it not do that

Related