Show a ManyToManyField as Checkboxes in Django Admin
From this answer it seems like it is possible to use ModelAdmin.formfield_overrides to override the ManyToManyField to use CheckBoxSelectMultiple:
from django.db import modelsfrom django.contrib import adminfrom django.forms import CheckboxSelectMultipleclass MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, }
I haven't tried it and am merely quoting from the source, but it seems plausible. Good luck.
Warning: as @errx rightly pointed out, the documentation highlights the following caveat:
If you want to use a custom widget with a relation field (i.e.
ForeignKey
or ManyToManyField), make sure you haven't included that field's name inraw_id_fields
orradio_fields
.
formfield_overrides
won't let you change the widget on relation fields that haveraw_id_fields
orradio_fields
set. That's becauseraw_id_fields
andradio_fields
imply custom widgets of their own.
This is most certainly possible. Here is the code which you can place in the ModelAdmin
subclass:
def formfield_for_manytomany(self, db_field, request=None, **kwargs): if db_field.name == 'your field name': kwargs['widget'] = form_widgets.CheckboxSelectMultiple() kwargs['help_text'] = '' return db_field.formfield(**kwargs)
This was derived from looking into the admin code.
To override for a single field the following is useful:
def get_form(self, request, obj=None, **kwargs): form = super(VNodeAdmin, self).get_form(request, obj, **kwargs) form.base_fields['node_type'].widget = forms.CheckboxSelectMultiple() return form