【问题标题】:How can i include a foreign key field in the "fields" tuple to make it appear on detail view page in Django Admin如何在“字段”元组中包含外键字段以使其显示在 Django Admin 的详细视图页面上
【发布时间】:2020-08-13 14:46:54
【问题描述】:

型号: 我有一个这样的模型

class TestModel1(models.Model):
    bookingid = models.ForeignKey(paymenttable)            // foreign key
    name = models.CharField(max_length=100, null=False, db_index=True)

    // I want this to be displayed in both the list view and detail view
    @property
    def custom_field(self):
       return self.bookingid.username  

Admin.py

class MyAdmin(ReadOnlyAdminFields,admin.ModelAdmin):

      // this works and i get custom_field in list view
      list_display = ('custom_field', 'name') 
      readonly = ('custom_field', 'name')

      // this dosent work and gives error  
      fields = ('custom_field', 'name')   

错误:未知字段 custom_field。检查 MyAdmin 类的字段/字段集/排除属性

【问题讨论】:

  • 对于fields 试试fields = ('bookingid__username', 'name')
  • @wfehr ,是的,试过这个,得到了同样的错误 - 未知字段 bookingid__username。检查 MyAdmin 类的字段/字段集/排除属性

标签: python django python-2.7 django-models django-admin


【解决方案1】:

你有一个小错字。 readonly 应该是 readonly_fields

小技巧,您可以将带有 short_description 属性的自定义标签添加到您的 custom_field 方法中。你可以这样做......

# models.py

class TestModel1(models.Model):
    bookingid = models.ForeignKey(paymenttable)
    name = models.CharField(max_length=100, null=False, db_index=True)

    @property
    def custom_field(self):
       return self.bookingid.username

    custom_field.short_description = "User"

然后您可以像这样在管理类的字段列表中使用它...

# admin.py

class MyAdmin(ReadOnlyAdminFields,admin.ModelAdmin):
      list_display = ('custom_field', 'name') 
      readonly_fields= ('custom_field', 'name')
      fields = ('custom_field', 'name')   

【讨论】:

  • 如果我使用 readonly_fields= ('name', 'custom_field') 这是有效的。但是,如果我只想将 custom_field 设为只读 - readonly_fields= ('custom_field') 那么它会给出相同的错误。这看起来很奇怪
  • 好吧,我错过了逗号 - readonly_fields= ('custom_field' , ) 。这很好用 另外要使用 custom_field.short_description = "User" ,我必须删除@property,对此有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多