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.
git-test/comments/admin.py

69 lines
2.4 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 _
# 批量禁用评论的admin动作
def disable_commentstatus(modeladmin, request, queryset):
queryset.update(is_enable=False)
# 批量启用评论的admin动作
def enable_commentstatus(modeladmin, request, queryset):
queryset.update(is_enable=True)
# 设置admin动作在后台显示的名称
disable_commentstatus.short_description = _('Disable comments')
enable_commentstatus.short_description = _('Enable comments')
# 评论模型的后台管理配置
class CommentAdmin(admin.ModelAdmin):
list_per_page = 20# 每页显示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]
# 外键字段使用原始ID输入框避免下拉列表性能问题
raw_id_fields = ('author', 'article')
# 搜索字段
search_fields = ('body',)
# 自定义方法:显示用户链接
def link_to_userinfo(self, obj):
# 获取用户模型的admin URL信息
info = (obj.author._meta.app_label, obj.author._meta.model_name)
link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
# 显示用户昵称或邮箱
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):
# 获取文章模型的admin URL信息
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(
u'<a href="%s">%s</a>' % (link, obj.article.title))
# 设置自定义方法的显示名称
link_to_userinfo.short_description = _('User')
link_to_article.short_description = _('Article')