Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to modify checkbox labels for MultipleChoiceField?

How do I modify (i.e. add classes or change the id) the labels for the checkboxes in a MultipleChoiceField?

In my form I have this MultipleChoiceField

    questions = forms.MultipleChoiceField(
        required=False,
        label='',
        widget=forms.CheckboxSelectMultiple,
        choices=CHOICES,
    )

and when I use the form in my template the checkboxes get rendered with individual labels around them like this.

<label for="id_questions_0">
    <input type="checkbox" name="questions" value="0">
    "the question"
</label>

How do I edit the label so that I can add a class to it and change other attributes of the label?

like image 632
bab Avatar asked Jun 03 '13 01:06

bab


1 Answers

You can use Widget.attrs, specifically:

questions = forms.MultipleChoiceField(
    required=False,
    label='',
    widget=forms.CheckboxSelectMultiple(attrs={'class': 'my-class'}),
    choices=CHOICES,
)

This would apply my-class to the radio select. If you still need to add class to the label as rendered, you'll need to customize forms.RadioSelect.

like image 98
yuwang Avatar answered Nov 09 '22 04:11

yuwang