您好,我正在尝试在 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/