Reputation: 2169
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?
Upvotes: 7
Views: 5674
Reputation: 961
Thanks, @yuwang, thrilled to see that this also works for ModelMultipleChoiceField (which allows you to display multiple checkboxes), as you can see below. There's very little documentation on ModelMultipleChoiceFields, so I wanted to share.
class ProposedFlagForm(ModelForm):
id = CharField(widget=HiddenInput())
crs_sched_proposed_course = CharField(widget=HiddenInput())
enrollment_flag = ModelMultipleChoiceField(required=False,
label='',
queryset=EnrollmentFlag.objects.all()\
.exclude(display='')\
.order_by('display'),
widget=CheckboxSelectMultiple)
class Meta:
model = CrsSchedProposedFlag
exclude = ('_updated','_updatedby')
#end Meta class
#end ProposedFlagForm
Upvotes: 0
Reputation: 876
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
.
Upvotes: 5