Django 1.11 Horizontal choice field

Viewed 3653

I've just updated from Django 1.10 to 1.11.1. In my template new_house_edit.html I have the following:

{{ form.rating }}

models.py contain the following:

class NewHouse(models.Model):
    rating = models.IntegerField(choices=(
                                    (1, "1"),
                                    (2, "2"),
                                    (3, "3"),
                                    (4, "4"),
                                    (5, "5"),
                                    ),
                                    default=3
                            )

In forms.py I used to have the following:

class HorizontalRadioRenderer(forms.RadioSelect.renderer):
    def render(self):
        return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))

class NewHouseForm(forms.ModelForm):

    class Meta:
        model = NewHouse
        fields = (
                'rating',)
        widgets={
                "rating": forms.RadioSelect(renderer=HorizontalRadioRenderer),
                }

Which gave the following error AttributeError: type object 'RadioSelect' has no attribute 'renderer'. I tried to solve it by doing this which is not working:

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


class NewHouseForm(forms.ModelForm):

    class Meta:
        model = NewHouse
        fields = (
                'rating',)
        widgets={
                "rating": "rating": forms.ChoiceField(widget=HorizontalRadioSelect, choices=(1, 2, 3, 4, 5)),
                }

I now get the error AttributeError: 'ChoiceField' object has no attribute 'use_required_attribute'. Can anyone help me fix this?

3 Answers

I know this is quite an old question but having spent some time today trying the different methods in various threads (after upgrading from 1.8 to 1.11) here is my solution.

For each radio group, define the following in the template (where "radio_list" is the name of the field):

{% for radio in radio_list %}
    {{ radio }}
{% endfor %} 

This is it at its simplest. Easy eh? You can basically apply any styling you want. It's all in the documentation in the RadioSelect section.

The moral of this little tale? Read the docs. Django is probably the best-documented app I have ever worked with. If I had done it earlier it would have saved me a lot of wasted time today when I could have been doing something more interesting.

Hope this helps someone.

Related