About Checkbox Lists for Many-to-many Relations in Administration
If you have a many-to-many relationship with a few choices, it makes sense to list the choices as a checkbox list. To do that, use formfield_overrides as follows:
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {
"widget": forms.CheckboxSelectMultiple,
},
}
Just make sure not to list the many-to-many fields in raw_id_fields or autocomplete_fields.
If you want to set the CheckboxSelectMultiple widget only to one specific many-to-many relation of a model, you can overwrite the ModelForm for the admin and specify the field with that widget there.
Tips and Tricks Programming Django 5.2 Django 4.2 Django 3.2
Also by me
Django Messaging 🎅🏼
For Django-based social platforms.
Django Paddle Subscriptions 🎅🏼
For Django-based SaaS projects.
Django GDPR Cookie Consent 🎅🏼
For Django websites that use cookies.