from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
#jrx: 批量禁用评论的动作
def disable_commentstatus(modeladmin, request, queryset):
queryset.update(is_enable=False)
#jrx: 批量启用评论的动作
def enable_commentstatus(modeladmin, request, queryset):
queryset.update(is_enable=True)
disable_commentstatus.short_description = _('Disable comments')
enable_commentstatus.short_description = _('Enable comments')
class CommentAdmin(admin.ModelAdmin):
#jrx: 每页显示20条评论
list_per_page = 20
#jrx: 列表页显示的字段
list_display = (
'id',
'body',
'link_to_userinfo',
'link_to_article',
'is_enable',
'creation_time')
#jrx: 列表页可点击跳转的字段
list_display_links = ('id', 'body', 'is_enable')
#jrx: 筛选器(按是否启用)
list_filter = ('is_enable',)
#jrx: 编辑页排除的字段(创建时间和修改时间不允许手动编辑)
exclude = ('creation_time', 'last_modify_time')
#jrx: 自定义动作(批量启用/禁用)
actions = [disable_commentstatus, enable_commentstatus]
#jrx: 生成评论作者的后台编辑链接
def link_to_userinfo(self, obj):
#jrx: 获取用户模型的app标签和模型名称
info = (obj.author._meta.app_label, obj.author._meta.model_name)
#jrx: 生成用户编辑页URL
link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
#jrx: 返回HTML格式的链接(显示昵称或邮箱)
return format_html(
u'%s' %
(link, obj.author.nickname if obj.author.nickname else obj.author.email))
#jrx: 生成评论关联文章的后台编辑链接
def link_to_article(self, obj):
#jrx: 获取文章模型的app标签和模型名称
info = (obj.article._meta.app_label, obj.article._meta.model_name)
#jrx: 生成文章编辑页URL
link = reverse('admin:%s_%s_change' % info, args=(obj.article.id,))
#jrx: 返回HTML格式的链接(显示文章标题)
return format_html(
u'%s' % (link, obj.article.title))
#jrx: 自定义字段在列表页的显示名称
link_to_userinfo.short_description = _('User')
link_to_article.short_description = _('Article')