我一直在尝试在 Django admin 中解决这个问题,但仍然找不到文档。
In my 模型.py,我有以下代码:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', blank=False)
class Author(models.Model):
first_name = models.CharField('First Name',max_length=50)
last_name = models.CharField('Last Name', max_length=50, blank=True)
description = models.CharField(max_length=500, blank=True)
def __str__(self):
return (self.first_name + ' ' + self.last_name)
and in admin.py从 django.contrib 导入 admin
# Register your models here.
from .models import Author, Post
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'get_author_description']
admin.site.register(Post, PostAdmin)
但是,每次运行服务器时,我都会收到错误
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of
'list_display[2]' refers to 'get_author_description', which is not a
callable, an attribute of 'PostAdmin', or an attribute or method on
'blog.Post'.
我已经阅读了很多有关此的文档,但仍然无济于事。有接受者吗?
最终编辑我决定保留最初提出问题的帖子。最终的解决方案只需要改变PostAdmin
.
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'author_description',]
def author_description(self, obj):
return obj.author.description
author_description.short_description = 'The Author Description'
需要注意的关键事项是:
- 方法
author_description
需要与类具有相同的缩进。另外,还需要返回obj.author.description
正如我们所指的作者对象。get_author_description
根本不需要(你可以说这是一种干扰)。