Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

The problem with Django's default Radio button widget is that it puts the buttons in a vertical format and the documentation is somewhat silent on how to make them horizontal. If you are dealing with a long list of buttons then veritical is probably the way to go but if you are dealing with "YES/NO" situation or any other boolean choice then you will probably want them horizontal. 

So let's start off by adding the following class to our forms.py[or comparable] module:

Code Block
class HorizRadioRenderer(forms.RadioSelect.renderer):
    """ this overrides widget method to put radio buttons horizontally
        instead of vertically.
    """
    def render(self):
            """Outputs radios"""
            return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))

Then within the same form.py module we can define our class form using the widget.

Code Block
class PartAForm(forms.Form):
    us_citizen = forms.CharField(label="Are you a US Citizen?",
                                 widget=forms.RadioSelect(renderer=HorizRadioRenderer,
                                 choices=(('yes','YES'),('no','NO'))), required=True)
    first_name = forms.CharField(label="First Name",
                 widget=forms.TextInput(attrs={'size':'12'}), required=False)
    middle_name = forms.CharField(label="Middle Name",
                  widget=forms.TextInput(attrs={'size':'12'}), required=False)
    last_name = forms.CharField(label="Last Name",
                widget=forms.TextInput(attrs={'size':'16'}), required=False)

The class "HorizRadioRenderer" is sent to the RadioSelect widget as a new renderer and displays the buttons on the horizontal not vertical.