views:

1246

answers:

3

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

choices = ( (1,'Yes'),
            (0,'No'),
          )

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.

+2  A: 

Use TypedChoiceField.

class EmailEditForm(forms.ModelForm):
    to_send_form = forms.TypedChoiceField(
                         choices=choices, widget=forms.RadioSelect, coerce=int
                    )

I don't know what you mean by 'more problems' when you used BooleanField - can you give some examples?

Daniel Roseman
note that choices is a sequence of pairs (see http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ChoiceField). Not quite sure what's in the pairs, tho.
dfrankow
I looked in widgets.py, choices is a list of tuples of the form (choice_value, choice_label).
dfrankow
+1  A: 

Use this if you want the horizontal renderer.

http://djangosnippets.org/snippets/1956/

Coc
+1  A: 
field = BooleanField(widget=RadioSelect(choices=YES_OR_NO), required=False)


YES_OR_NO = (
    (True, 'Yes'),
    (False, 'No')
)
Mark