From a8dcf5aa392ee8d2be70483060adf78988054e8b Mon Sep 17 00:00:00 2001 From: plhw57tbe <2723863608@qq.com> Date: Sun, 12 Oct 2025 22:08:12 +0800 Subject: [PATCH] Update admin.py --- src/DjangoBlog-master/comments/admin.py | 41 ++++++++++++++++++------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/src/DjangoBlog-master/comments/admin.py b/src/DjangoBlog-master/comments/admin.py index a814f3f..8abfe4e 100644 --- a/src/DjangoBlog-master/comments/admin.py +++ b/src/DjangoBlog-master/comments/admin.py @@ -1,47 +1,66 @@ -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 _ +from django.contrib import admin # 导入Django管理后台模块 +from django.urls import reverse # 导入reverse函数,用于生成URL +from django.utils.html import format_html # 导入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): + # 管理后台列表页每页显示20条记录 list_per_page = 20 + # 列表页显示的字段 list_display = ( - 'id', - 'body', - 'link_to_userinfo', - 'link_to_article', - 'is_enable', - 'creation_time') + '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标签和模型名称 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'%s' % (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'%s' % (link, obj.article.title)) + # 设置自定义字段在列表页的显示名称(支持国际化) link_to_userinfo.short_description = _('User') - link_to_article.short_description = _('Article') + link_to_article.short_description = _('Article') \ No newline at end of file