我一直试图在Django管理员中解决这个问题,但仍无法找到文档。
在我的 models.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)
并在 admin.py 中 来自django.contrib import 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
(你可以说这是一种分心)。答案 0 :(得分:8)
您可以在admin类中使用自定义方法:
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'author_description']
def author_description(self, obj):
return obj.author.get_author_description()
此外,您可以自定义格式化自定义方法中的字段或属性。如果该方法将返回HTML,则可以在该方法之后在类中添加以下内容:
author_description.allow_tags = True
最后,如果您要为此方法添加自定义详细名称:
author_description.short_description = "My awesome name"