Align radio buttons horizontally in django 1.11

2,685 views
Skip to first unread message

BIJAL MANIAR

unread,
Apr 19, 2017, 9:11:31 AM4/19/17
to Django users

Hi,

I'm trying to upgrade existing application from 1.4 to 1.11.
Below snippet of code to align radio buttons horizontally is working fine with django 1.4

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),
                                 )
But getting below error with django 1.11. 
AttributeError: type object 'RadioSelect' has no attribute 'renderer'.
Is it due to introduction of template based widget rendering. Is there any link on how to implement it?

Any help would be appreciated. Thanks!

Tim Graham

unread,
Apr 22, 2017, 10:42:46 AM4/22/17
to Django users
You could use a custom widget template, e.g.

class HorizontalRadioSelect(forms.RadioSelect):
template_name = '...'

...

forms.ChoiceField(..., widget=HorizontalRadioSelect)

See https://docs.djangoproject.com/en/stable/ref/forms/renderers/ for more details.

Or you could add a CSS class and style the output using CSS.

widget=forms.RadioSelect(attrs={'class': 'inline'})

The admin uses this approach:
https://github.com/django/django/blob/c52ae33a0c0c0bbaa460607a8787e95fe983a2b9/django/contrib/admin/static/admin/css/forms.css#L42-L66
https://github.com/django/django/blob/c52ae33a0c0c0bbaa460607a8787e95fe983a2b9/django/contrib/admin/options.py#L64-L65

It was inadvertently broken in Django 1.11 but will be fixed in 1.11.1 (due out around May 1).
https://code.djangoproject.com/ticket/28059
Reply all
Reply to author
Forward
0 new messages