Search code examples
djangoformsradio-buttonalignment

Align radio buttons horizontally in django forms


HI

I want to align the radio buttons horizontally. By default django forms displays in vertical format.

feature_type  = forms.TypedChoiceField(choices = formfields.FeatureType, widget = forms.RadioSelect)

Is there any special parameter that we can pass for radio buttons alignment?

Thanks in advance


Solution

  • Thats the behavior of the RadioField. If you want it rendered horizontally, create a horizontal renderer, like something as follows:

    from django.utils.safestring import mark_safe
    
    class HorizontalRadioRenderer(forms.RadioSelect.renderer):
      def render(self):
        return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))
    
    
    class ApprovalForm(forms.Form):
        approval = forms.ChoiceField(choices=APPROVAL_CHOICES,
                     initial=0,
                     widget=forms.RadioSelect(renderer=HorizontalRadioRenderer),
                                     )