我创建了一个自定义管理类来在我的Django应用中显示Comments Admin。我想要做的是“对象ID”下的项目链接到各自对象的编辑对象页面。我将如何实现这一目标?
我的评论管理员:
class MyCommentsAdmin(admin.ModelAdmin):
fieldsets = (
(_('Content'),
{'fields': ('user', 'user_name', 'user_email', 'user_url', 'comment')}
),
(_('Metadata'),
{'fields': ('submit_date', 'ip_address', 'is_public', 'is_removed')}
),
)
list_display = ('id', 'name', 'comment', 'content_type', 'object_pk', 'ip_address', 'submit_date', 'is_public', 'is_removed')
list_filter = ('submit_date', 'site', 'is_public', 'is_removed')
date_hierarchy = 'submit_date'
list_display_links = ('id','comment',)
ordering = ('-submit_date',)
raw_id_fields = ('user',)
search_fields = ('comment', 'user__username', 'user_name', 'user_email', 'ip_address')
admin.site.unregister(Comment)
admin.site.register(Comment, MyCommentsAdmin)
谢谢!
答案 0 :(得分:13)
在管理类上定义自定义方法,并在list_display
元组中引用该方法。
from django.core.urlresolvers import reverse
class MyCommentsAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'comment', 'content_type', 'object_link', 'ip_address', 'submit_date', 'is_public', 'is_removed')
list_select_related = True
def object_link(self, obj):
ct = obj.content_type
url = reverse('admin:%s_%s_change' % (ct.app_label, ct.model), args=(obj.id,))
return '<a href="%s">%s</a>' % (url, obj.id)
object_link.allow_tags = True
注意我添加了list_select_related=True
,因为object_link方法引用了content_type模型,否则会导致一大堆额外查询。