[Answer]-Add css class from database to manytomany field

1👍

You will probably need to add a custom class that extends Django’s CheckboxSelectMultiple, which can be used for M2M relationships. You’ll find it in: django.forms.widgets. In that class, is a render method that you can override.

Example:

class BootstrapCheckboxSelectMultiple(CheckboxSelectMultiple):
    """Form widget that supports Bootstrap's markup requirements"""
    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 = []
        # 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.

            # Should be able to pass in additional widget attributes to
            # the checkbox renderer here...
            if has_id:
                final_attrs = dict(final_attrs, id='{}_{}'.format(attrs['id'], i))
                label_for = u' for="{}"'.format(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'<label{} class="checkbox">{} {}</label>'.format(
                label_for, rendered_cb, option_label))
        return mark_safe(u'\n'.join(output))

Then specify the class for your field:

class PersonForm(ModelForm):
    ...

    class Meta:
        widgets = {'person_interests': BootstrapCheckboxSelectMultiple,
                   'person_psycho': forms.HiddenInput}
        model = Person

Of course, you can name the class whatever you want. Hope that helps you out.

Leave a comment