在 Django Admin 中将 ManyToManyField 显示为复选框
问题描述
Is there a simple way to show a ManyToManyField as Checkboxes in Django Admin? Thanks in advance!
解决方案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 models
from django.contrib import admin
from django.forms import CheckboxSelectMultiple
class 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.
ForeignKeyor ManyToManyField), make sure you haven't included that field's name inraw_id_fieldsorradio_fields.
formfield_overrideswon't let you change the widget on relation fields that haveraw_id_fieldsorradio_fieldsset. That's becauseraw_id_fieldsandradio_fieldsimply custom widgets of their own.
相关文章