记录一下
使用from django.utils.html import format_html
return format_html
例子:
from django.contrib import admin
from .models import Article, Category, Tag
from django.utils.html import format_html
Register your models here.
class ArticleAdmin(admin.ModelAdmin):
'''设置列表可显示的字段'''
list_display = ('title', 'author', 'status', 'mod_date', 'show_tags')
'''展示tags'''
def show_tags(self, obj):
tag_list = []
tags = obj.tags.all()
if tags:
for tag in tags:
tag_list.append(tag.name)
return ','.join(tag_list)
else:
return format_html(
'<span style="color:red;">文章{}无标签</span>',
obj.id,)
'''设置表头'''
show_tags.short_description = '标签' # 设置表头
admin.site.register(Article, ArticleAdmin)
转载:https://zhuanlan.zhihu.com/p/48424043
这篇博客介绍了如何在 Django 的行政管理界面(Admin)中自定义模型显示,特别是展示了如何创建一个 `show_tags` 方法来显示文章的标签。通过 `format_html` 函数,可以安全地在列表视图中显示带有样式的标签信息,当文章没有标签时,会显示红色提示。同时,还注册了 `Article` 模型到 Django admin 站点。
1009

被折叠的 条评论
为什么被折叠?



