简体   繁体   中英

How can i include a foreign key field in the “fields” tuple to make it appear on detail view page in Django Admin

Models: I have a model like this

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')   

Error: Unknown field(s) custom_field. Check fields/fieldsets/exclude attributes of MyAdmin class

You have a small typo. readonly should be readonly_fields

A little hack, you can add a custom label with short_description property to your custom_field method. You can do it like this...

# 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"

Then you can use it in your list of fields in your admin class like this...

# admin.py

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM