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

70 lines
2.5 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
from django.utils.translation import gettext_lazy as _
# 批量禁用评论(将 is_enable 设为 False
def disable_commentstatus(modeladmin, request, queryset):
queryset.update(is_enable=False)
# 批量启用评论(将 is_enable 设为 True
def enable_commentstatus(modeladmin, request, queryset):
queryset.update(is_enable=True)
# 定义动作名称,在 Django Admin 批量操作菜单中显示的文字
disable_commentstatus.short_description = _('Disable comments')
enable_commentstatus.short_description = _('Enable comments')
class CommentAdmin(admin.ModelAdmin):
# 每页显示评论数量
list_per_page = 20
# 在评论列表中显示哪些字段
list_display = (
'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):
# 获取目标 admin change 页面的 URL 路径
info = (obj.author._meta.app_label, obj.author._meta.model_name)
link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
# 显示用户昵称,若无昵称显示 email
return format_html(
'<a href="{}">{}</a>'.format(
link,
obj.author.nickname if obj.author.nickname else obj.author.email
)
)
# 显示所属文章,并可点击跳转到文章编辑页面
def link_to_article(self, obj):
info = (obj.article._meta.app_label, obj.article._meta.model_name)
link = reverse('admin:%s_%s_change' % info, args=(obj.article.id,))
return format_html('<a href="{}">{}</a>'.format(link, obj.article.title))
# 设置在后台列表中显示的列标题
link_to_userinfo.short_description = _('User')
link_to_article.short_description = _('Article')