def colored_name(self): if self.狀態 == 'Y': color_code = 'green' else: color_code = 'red' return format_html( '<span style="color:{};">{}</span>', color_code, self.狀態 )
但如果你給這個方法添加一個boolean的屬性並賦值為True,它將顯示為on/off的圖標,如下圖:
from django.db import models from django.contrib import admin class Person(models.Model): first_name = models.CharField(max_length=50) birthday = models.DateField() def born_in_fifties(self): return self.birthday.strftime('%Y')[:3] == '195' # 關鍵在這里 born_in_fifties.boolean = True class PersonAdmin(admin.ModelAdmin): # 官方文檔這里有錯,將'name'改為'first_name' list_display = ('first_name', 'born_in_fifties')

但是,我們看到標題並不是我們想要的,那么如何設置標題呢?
添加一行代碼:colored_status.short_description = u"狀態"
