Display a boolean model field in a django form as a radio button rather than the default Checkbox

0 votes
asked Jun 23, 2009 by lakshman-prasad

This is how I went about, to display a Boolean model field in the form as Radio buttons Yes and No.

choices = ( (1,'Yes'),

class EmailEditForm(forms.ModelForm):

    #Display radio buttons instead of checkboxes
    to_send_form = forms.ChoiceField(choices=choices,widget=forms.RadioSelect)

    class Meta:
    model = EmailParticipant
    fields = ('to_send_email','to_send_form')

    def clean(self):
    A workaround as the cleaned_data seems to contain u'1' and u'0'. There may be a better way.

    self.cleaned_data['to_send_form'] = int(self.cleaned_data['to_send_form'])
    return self.cleaned_data

As you can see in the code above, I need a clean method that converts input string to an integer, which may be unnecessary.

Is there a better and/or djangoic way to do this. If so, how?

And no, using BooleanField seems to cause a lot more problems. Using that seemed obvious to me; but it isn't. Why is it so.

4 Answers

0 votes
answered Jun 23, 2009 by daniel-roseman

Use TypedChoiceField.

class EmailEditForm(forms.ModelForm):
    to_send_form = forms.TypedChoiceField(
                         choices=choices, widget=forms.RadioSelect, coerce=int
0 votes
answered Jun 17, 2010 by mpen
field = BooleanField(widget=RadioSelect(choices=YES_OR_NO), required=False)

    (True, 'Yes'),
    (False, 'No')
0 votes
answered Jun 30, 2010 by coc-b

Use this if you want the horizontal renderer.


0 votes
answered Sep 15, 2017 by jhrr

If you want to deal with booleans instead of ints this is the way to do it.

    choices=((True, 'Yes'), (False, 'No')),
    coerce=lambda x: x == 'True'
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter