且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果表达式为 True,则更改 Django 管理界面中字段的字体/颜色

更新时间:2023-09-18 19:18:16

这是一个老问题,但我会从 Django 1.10 的文档中添加一个示例,因为 allow_tagsDjango 1.9 起,已接受的答案中使用的属性已被弃用,建议使用 format_html 代替:

This is an old question but I'll add an example from docs for Django 1.10 because allow_tags attribute used in the accepted answer is deprecated since Django 1.9 and it is recommended to use format_html instead:

from django.db import models
from django.contrib import admin
from django.utils.html import format_html

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    color_code = models.CharField(max_length=6)

    def colored_name(self):
        return format_html(
            '<span style="color: #{};">{} {}</span>',
            self.color_code,
            self.first_name,
            self.last_name,
        )

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'colored_name')