You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DjangoBlog/comments/admin.py

64 lines
2.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html # 用于安全渲染HTML内容
from django.utils.translation import gettext_lazy as _ # 用于国际化翻译
# 自定义批量操作:禁用选中的评论
def disable_commentstatus(modeladmin, request, queryset):
# 将选中评论的is_enable字段批量更新为False
queryset.update(is_enable=False)
# 自定义批量操作:启用选中的评论
def enable_commentstatus(modeladmin, request, queryset):
# 将选中评论的is_enable字段批量更新为True
queryset.update(is_enable=True)
# 为批量操作设置显示名称(支持国际化)
disable_commentstatus.short_description = _('Disable comments')
enable_commentstatus.short_description = _('Enable comments')
class CommentAdmin(admin.ModelAdmin):
"""评论模型的Admin配置类控制后台评论管理界面的展示和功能"""
list_per_page = 20 # 每页显示20条评论
list_display = (
'id', # 评论ID
'body', # 评论内容
'link_to_userinfo', # 自定义字段:评论作者的链接
'link_to_article', # 自定义字段:评论所属文章的链接
'is_enable', # 是否启用
'creation_time' # 创建时间
)
list_display_links = ('id', 'body', 'is_enable') # 列表中可点击跳转编辑页的字段
list_filter = ('is_enable',) # 右侧筛选器:按是否启用筛选
exclude = ('creation_time', 'last_modify_time') # 编辑页排除的字段(不允许手动修改)
actions = [disable_commentstatus, enable_commentstatus] # 注册批量操作
def link_to_userinfo(self, obj):
"""自定义列表字段:生成评论作者的后台编辑页链接"""
# 获取作者模型的app标签和模型名称用于反向生成URL
info = (obj.author._meta.app_label, obj.author._meta.model_name)
# 反向生成作者模型的编辑页URL
link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
# 渲染为HTML链接优先显示昵称无昵称则显示邮箱
return format_html(
u'<a href="%s">%s</a>' %
(link, obj.author.nickname if obj.author.nickname else obj.author.email)
)
def link_to_article(self, obj):
"""自定义列表字段:生成评论所属文章的后台编辑页链接"""
# 获取文章模型的app标签和模型名称
info = (obj.article._meta.app_label, obj.article._meta.model_name)
# 反向生成文章模型的编辑页URL
link = reverse('admin:%s_%s_change' % info, args=(obj.article.id,))
# 渲染为HTML链接显示文章标题
return format_html(u'<a href="%s">%s</a>' % (link, obj.article.title))
# 为自定义字段设置显示名称(支持国际化)
link_to_userinfo.short_description = _('User')
link_to_article.short_description = _('Article')