在 Django 管理员中,我希望 非常喜欢 能够在列表显示中显示可编辑的 ManyToManyField。
它不一定需要是完整的 ManyToManyField 控件 - 能够仅保存一个值就足以满足列表显示的目的(尽管基础值本质上是多对多的)。
我的模型看起来像这样:
class Item(models.Model):
name = models.CharField(max_length=500)
colour = models.ManyToManyField(Colour, related_name='primary_colour')
如果我在
admin.py
中尝试这个:class ItemAdmin(admin.ModelAdmin):
list_display = ('name', 'colour')
list_editable = ('colour')
然后我收到这个错误:
'ItemAdmin.list_display[6]', 'colour' is a ManyToManyField which is not supported.
是否有任何方式 可以显示可编辑的 ManyToManyField 以便在列表显示中快速编辑?
我发现了这个相关的问题,它解释了如何使列表显示中的值可见,但不可编辑:ManyToManyField widget in a django admin change list?
最佳答案
默认情况下,Django 不允许在 ModelAdmin 的 list_editable 中添加 ManyToManyField。所以我们需要覆盖模型管理方法。
在查看模型时,您需要按照以下步骤在列表显示页面中获得可编辑的 ManyToManyField。
在 apps/forms.py 中,您需要定义需要在列表显示页面中编辑哪些多对多字段。如下,
from django import forms
from app.models import Item
class ItemChangeListForm(forms.ModelForm):
# here we only need to define the field we want to be editable
colour = forms.ModelMultipleChoiceField(queryset=Colour.objects.all(),
required=False)
在 app/admin.py 中,您需要覆盖模型管理员的方法。如下,
from django.contrib import admin
from django.contrib.admin.views.main import ChangeList
from app.models import Item
from app.forms import ItemChangeListForm
class ItemChangeList(ChangeList):
def __init__(self, request, model, list_display,
list_display_links, list_filter, date_hierarchy,
search_fields, list_select_related, list_per_page,
list_max_show_all, list_editable, model_admin):
super(ItemChangeList, self).__init__(request, model,
list_display, list_display_links, list_filter,
date_hierarchy, search_fields, list_select_related,
list_per_page, list_max_show_all, list_editable,
model_admin)
# these need to be defined here, and not in ItemAdmin
self.list_display = ['action_checkbox', 'name', 'colour']
self.list_display_links = ['name']
self.list_editable = ['colour']
class ItemAdmin(admin.ModelAdmin):
def get_changelist(self, request, **kwargs):
return ItemChangeList
def get_changelist_form(self, request, **kwargs):
return ItemChangeListForm
admin.site.register(Item, ItemAdmin)
现在您都设置检查更改,运行服务器并检查电影模型的 django admin。您可以直接从列表显示页面编辑 ManyToMany 字段。
注意 :如果您打算在列表中使用多个可编辑的 ManyToManyFields,则需要在 settings.py 中设置 DATA_UPLOAD_MAX_NUMBER_FIELDS 。
关于Django 管理员 : ManyToManyField in list_editable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15655587/