python - django admin 内联多对多自定义字段

标签 python django django-forms django-admin django-1.5

您好,我正在尝试在 Django 管理中自定义我的内联。

这是我的模型:

class Row(models.Model):
    name = models.CharField(max_length=255)

class Table(models.Model):
    rows = models.ManyToManyField(Row, blank=True)
    name = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name

和我的管理员:

class RowInline(admin.TabularInline):
    model = Table.rows.through
    fields = ['name']


class TableAdmin(admin.ModelAdmin):
    inlines = [
        RowInline,
    ]
    exclude = ('rows',)

但是我得到这个错误

ImproperlyConfigured at /admin/table_app/table/1/

'RowInline.fields' refers to field 'name' that is missing from the form.

这怎么可能?

最佳答案

class RowInline(admin.TabularInline):
    model = Table.rows.through
    fields = ['name']

这会带来一个问题,因为 Table.rows.through 代表一个中间模型。如果您想更好地理解这一点,请查看您的数据库。您将看到一个引用此模型的中间表。它的名称可能类似于 apname_table_rows。此中间模型不包含名称字段。它只有两个外键字段:表和行。 (并且它有一个 id 字段。)

如果您需要名称,可以通过行关系将其作为只读字段引用。

class RowInline(admin.TabularInline):
    model = Table.rows.through
    fields = ['row_name']
    readonly_fields = ['row_name']

    def row_name(self, instance):
        return instance.row.name
    row_name.short_description = 'row name'


class TableAdmin(admin.ModelAdmin):
    inlines = [
        RowInline,
    ]
    exclude = ('rows',)

关于python - django admin 内联多对多自定义字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19807757/

相关文章:

python - Django:保存后ID为空

python - 使用模型实例中的数据加载 Django 表单对象 "loaded"

python - 从 Django 模型中获取单个字段的过滤值列表

django - 将参数传递给 django admin 中的内联表单

python - Django Sites Framework 初始设置

django - 如何获取模板中表单的外键值?

python - 将函数应用于列表的每个元素

python - 尝试生成 5 个随机项目,有时会生成 4 个

python - 为什么 python 列表会这样做?

python - numpy -- 将非连续数据转换为连续数据