p.ry
p.ry

Reputation: 489

How do i give class attribute to the label of checkbox from the django form

In forms.py,

aminities = forms.MultipleChoiceField(choices= dicto.aminites_dic.items(), 
required=False,widget=forms.CheckboxSelectMultiple(attrs= 
{'name':'list_details[]','class':'amini'}))

In the template,

{% for check in form.aminities %}
      {{check}}
    {% endfor %}

Upvotes: 1

Views: 1063

Answers (1)

dirkgroten
dirkgroten

Reputation: 20672

In general, rather than spelling out the entire field in the template (using a for-loop and explicitely rendering the choice_label), you should subclass the widget and replace the template.

class SpecialCheckboxSelectMultiple(CheckboxSelectMultiple):
    option_template_name = "myapp/widgets/checkbox_option.html"

Then in checkbox_option.html you customize the code basing it on the original Django code (which you can find in django/forms/widgets/input_option.html):

{% if wrap_label %}
    <label{% if widget.attrs.id %} for="{{ widget.attrs.id }}"{% endif %} class="amini">
{% endif %}
{% include "django/forms/widgets/input.html" %}
{% if wrap_label %} {{ widget.label }}</label>{% endif %}

Here you can just add your own classes to the label. That way in your template you only need to call {{ check }}, and it will use your custom <label>

Upvotes: 1

Related Questions