gpt4 book ai didi

python - 如何在 Django 管理列表显示页面中编辑 ManyToManyField?

转载 作者:行者123 更新时间:2023-11-30 22:11:45 25 4
gpt4 key购买 nike

我想在 Django 管理 list_display 页面中添加可编辑的 Many2Many 字段。模型结构如下,

class Genre(models.Model):
name = models.CharField(max_length=250, unique=True)


class Movie(models.Model):
name = models.CharField(max_length=250)
genre = models.ManyToManyField(Genre)

我尝试过,

class MovieAdmin(admin.ModelAdmin):
list_display = ['name', 'genre']
list_editable = ['genre']

上面抛出了一个错误。

最佳答案

默认情况下,Django 不允许在 ModelAdmin 的 list_editable 中添加 ManyToManyField。因此我们需要重写模型管理方法。

在查看模型时,您需要按照以下步骤操作,才能在列表显示页面中获得可编辑的 ManyToManyField。

apps/forms.py您需要定义哪些ManyToMany字段需要在列表显示页面中进行编辑。如下,

from django import forms
from app.models import Genre


class MovieChangeListForm(forms.ModelForm):

# here we only need to define the field we want to be editable
genre = forms.ModelMultipleChoiceField(queryset=Genre.objects.all(),
required=False)

app/admin.py您需要覆盖模型管理的方法。如下,

from django.contrib import admin
from django.contrib.admin.views.main import ChangeList
from app.models import Movie
from app.forms import MovieChangeListForm

class MovieChangeList(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(MovieChangeList, 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 MovieAdmin
self.list_display = ['action_checkbox', 'name', 'genre']
self.list_display_links = ['name']
self.list_editable = ['genre']


class MovieAdmin(admin.ModelAdmin):

def get_changelist(self, request, **kwargs):
return MovieChangeList

def get_changelist_form(self, request, **kwargs):
return MovieChangeListForm


admin.site.register(Movie, MovieAdmin)

现在您已准备好检查更改,运行服务器并检查 django admin 的电影模型。您可以直接从列表显示页面编辑ManyToMany字段。

注意:如果您要在列表中使用多个可编辑的ManyToManyFields,则需要在settings.py中设置DATA_UPLOAD_MAX_NUMBER_FIELDS .

关于python - 如何在 Django 管理列表显示页面中编辑 ManyToManyField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51325438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com