django管理员内联许多到许多自定义字段 [英] django admin inline many to many custom fields

查看:476
本文介绍了django管理员内联许多到许多自定义字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下是我的模型:

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

类表(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',)

但是我收到这个错误


在/ admin / table_app / table中配置不正确/ 1 /



'RowInline.fields'是指
表单中缺少的字段'name'。


< blockquote>

怎么可能?

解决方案

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

这是一个问题,因为表。 rows.through表示一个中间模型。如果您想了解更好,请查看您的数据库。您将看到一个引用此模型的中间表。它可能被命名为apname_table_rows。这个中间模型不包含字段,名称。它只有两个外键字段:表和行。 (并且它有一个id字段。)



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

  class RowInline(admin.TabularInline):
model = Table.rows.through
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',)


Hi I am trying to customize my inlines in django admin.

Here are my models:

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

and my admin:

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


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

However I get this error

ImproperlyConfigured at /admin/table_app/table/1/

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

How is that possible ?

解决方案

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

This presents a problem because Table.rows.through represents an intermediate model. If you would like to understand this better have a look at your database. You'll see an intermediate table which references this model. It is probably named something like apname_table_rows. This intermeditate model does not contain the field, name. It just has two foreign key fields: table and row. (And it has an id field.)

If you need the name it can be referenced as a readonly field through the rows relation.

class RowInline(admin.TabularInline):
    model = Table.rows.through
    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',)

这篇关于django管理员内联许多到许多自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆