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.
tentest/doc/DjangoBlog/comments/admin.py

77 lines
3.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.

# FRR该模块用于配置Django后台系统中评论(Comment)模型的管理界面,
# 包括自定义列表展示、批量操作、字段过滤及关联对象链接等功能,
# 方便管理员在后台对评论数据进行高效管理。
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 _
# FRR自定义批量操作函数用于将选中的评论设置为"禁用"状态
def disable_commentstatus(modeladmin, request, queryset):
# FRR通过queryset批量更新is_enable字段为False
queryset.update(is_enable=False)
# FRR自定义批量操作函数用于将选中的评论设置为"启用"状态
def enable_commentstatus(modeladmin, request, queryset):
# FRR通过queryset批量更新is_enable字段为True
queryset.update(is_enable=True)
# FRR为批量操作函数设置在后台显示的名称支持国际化
disable_commentstatus.short_description = _('Disable comments')
enable_commentstatus.short_description = _('Enable comments')
# FRR评论模型(Comment)的后台管理配置类继承自Django默认的ModelAdmin
class CommentAdmin(admin.ModelAdmin):
# FRR每页显示20条评论数据
list_per_page = 20
# FRR列表页展示的字段包括自定义的关联对象链接字段
list_display = (
'id', # 评论ID
'body', # 评论内容
'link_to_userinfo', # 自定义字段:评论作者的链接
'link_to_article', # 自定义字段:评论所属文章的链接
'is_enable', # 是否启用
'creation_time' # 创建时间
)
# FRR列表页中可点击跳转详情页的字段
list_display_links = ('id', 'body', 'is_enable')
# LGM右侧过滤栏可按"是否启用"筛选评论
list_filter = ('is_enable',)
# FRR编辑页中排除的字段创建时间和最后修改时间通常自动生成不允许手动编辑
exclude = ('creation_time', 'last_modify_time')
# FRR注册批量操作函数在列表页顶部"动作"下拉框中显示
actions = [disable_commentstatus, enable_commentstatus]
# FRR将外键字段(author和article)显示为输入框(而非下拉框),适合数据量大的场景
raw_id_fields = ('author', 'article')
# FRR设置搜索框可搜索的字段按评论内容搜索
search_fields = ('body',)
# FRR自定义列表字段显示评论作者的链接点击可跳转到作者的后台编辑页
def link_to_userinfo(self, obj):
# FRR获取作者模型(author)的元数据用于生成admin链接
info = (obj.author._meta.app_label, obj.author._meta.model_name)
#FRR生成作者在admin后台的编辑页URL
link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
#FRR返回HTML格式的链接显示作者昵称若无昵称则显示邮箱
return format_html(
u'<a href="%s">%s</a>' %
(link, obj.author.nickname if obj.author.nickname else obj.author.email))
# FRR自定义列表字段显示评论所属文章的链接点击可跳转到文章的后台编辑页
def link_to_article(self, obj):
# FRR获取文章模型(article)的元数据用于生成admin链接
info = (obj.article._meta.app_label, obj.article._meta.model_name)
# FRR生成文章在admin后台的编辑页URL
link = reverse('admin:%s_%s_change' % info, args=(obj.article.id,))
# FRR返回HTML格式的链接显示文章标题
return format_html(
u'<a href="%s">%s</a>' % (link, obj.article.title))
# FRR设置自定义字段在列表页的表头名称支持国际化
link_to_userinfo.short_description = _('User')
link_to_article.short_description = _('Article')