Admin中Django的外键参考
我一直试图在Django admin中解决这个问题,但仍然找不到文档 在mymodels.py中,我有以下代码:Admin中Django的外键参考,django,python-3.4,Django,Python 3.4,我一直试图在Django admin中解决这个问题,但仍然找不到文档 在mymodels.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
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导入管理
# 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'.
需要注意的关键事项是:
- 方法
需要与类位于同一缩进中。此外,当我们引用author对象时,它需要返回author\u description
obj.author.description
完全不是必需的(你可以说这是一种干扰)get\u author\u description
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"
什么是
get\u author\u description
。我做错什么了吗(admin.E108)“list\u display[2]”的值指的是“author\u description”,它不是可调用的、“PostAdmin”属性,也不是“blog.Post”上的属性或方法。Post-Edited。请阅读并更新您的代码<代码>作者描述缩进不正确。我知道了!我会对帖子做一些修改,让它更清晰。“现在一切都有意义了,”路易斯马苏埃利说。author\u description
应该是PostAdmin
类中的def
,否则它将无法识别方法。我还要补充一点。最后一行应该是return obj.author.get\u author\u description()
,因为描述在author
类中,而不是Post
中。我在运行服务器时发现了它。@bryansis2010在author中获取了\u author\u description作为方法名,这似乎违反了DRYAgree@Foon的规定,我将在起草编辑后的答案时考虑到这一点。
author_description.short_description = "My awesome name"