forms.py
class TypeSelectionForm(forms.Form):
checkbox_field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), label=\"\", required=Fals
Widgets take an attrs attribute, which should add the attribute to each input. Try this:
checkbox_field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'my-image-class', }), label="", required=False)
UPDATE:
So it looks like the granular approach mentioned above only works for radio button widgets. But what you want is actually very simple. Just output your checkboxes as normal:
{% for field in types.checkbox_field %}
{{field}}
{% endfor %}
This will output your list of checkboxes as you need. Then just use a little CSS to style the background image of each list item:
form ul li {
background:url("") no-repeat center;
width:20px;
height:20px;
}
UPDATE
If you want to render the checkboxes differently, you need a custom widget class, as that's the widgets job. Something like this will get you going. I'd personally use the attrs option on the widget to add in a class, but I've hard coded it here to show you that what you ask is possible, just not pretty:
class CheckboxDivSelectMultiple(CheckboxSelectMultiple):
'''renders the checkboxes as divs with a hard coded class'''
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
has_id = attrs and 'id' in attrs
final_attrs = self.build_attrs(attrs, name=name)
output = [u'']
# Normalize to strings
str_values = set([force_unicode(v) for v in value])
for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
# If an ID attribute was given, add a numeric index as a suffix,
# so that the checkboxes don't all have the same ID attribute.
if has_id:
final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
label_for = u' for="%s"' % final_attrs['id']
else:
label_for = ''
cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
option_value = force_unicode(option_value)
rendered_cb = cb.render(name, option_value)
option_label = conditional_escape(force_unicode(option_label))
output.append(u'' % ('new-class', label_for, rendered_cb, option_label))
output.append(u'')
return mark_safe(u'\n'.join(output))
use it in your form:
checkbox_field = forms.MultipleChoiceField(widget=forms.CheckboxDivSelectMultiple(), label="", required=False)