在 Django Admin 中将 ManyToManyField 显示为复选框

Show a ManyToManyField as Checkboxes in Django Admin(在 Django Admin 中将 ManyToManyField 显示为复选框)

本文介绍了在 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. ForeignKey or ManyToManyField), make sure you haven't included that field's name in raw_id_fields or radio_fields.

formfield_overrides won't let you change the widget on relation fields that have raw_id_fields or radio_fields set. That's because raw_id_fields and radio_fields imply custom widgets of their own.

这篇关于在 Django Admin 中将 ManyToManyField 显示为复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 Django Admin 中将 ManyToManyField 显示为复选框

基础教程推荐