[Django]-Manytomany field in form with checkboxes insted select field in django template

4πŸ‘

βœ…

To show a ManyToManyField as checkboxes instead of a select field, you need to set the widget in the Meta class of the appropriate ModelForm subclass. Then to show a custom label on each checkbox, create your own form field class derived from ModelMultipleChoiceField, and override label_from_instance. You may also add HTML tags to the string returned by label_from_instance to make it look as pretty as you want, but remember to wrap the returned string with mark_safe.

from django.forms.widgets import CheckboxSelectMultiple
from django.forms.models import ModelMultipleChoiceField
...
class CustomSelectMultiple(ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "%s: %s %s" %(obj.name, obj.short_description, obj.price)

class BarForm(forms.ModelForm):
    foo = CustomSelectMultiple(queryset=Foo.objects.all())
    class Meta:
        model = Bar
        widgets = {"foo":CheckboxSelectMultiple(),}
πŸ‘€Simon Kagwi

Leave a comment