如何根据模型值在 Django Admin 图标中显示
How to show in Django Admin Icons based on model value
我需要在列表中显示 Django Admin 中的图标并根据值更改视图。
例如:
如果模型字段 eventId
具有值 1
,则显示图标(png 或 webfont)
这可能吗?
型号:
class Events(models.Model):
eventId = models.CharField(_('EventID'), max_length=254, null=False, blank=False, default='', )
name = models.CharField(_('EventName'), max_length=254, null=False, blank=False, default='', )
euuid = models.UUIDField(_('UUID'), default=uuid.uuid4, editable=False, unique=True)
created = models.DateTimeField(_('Created'), auto_now_add=True, blank=True, help_text=_('Date of the creation'))
您创建一个类似 icon() 的方法并将其添加到 list_display 字段并将其设为只读。
from django.utils.html import format_html
class EventsAdmin(admin.ModelAdmin):
...
...
list_display = ['your_list_display_fields', 'icon']
fields = ['your_model_fields_for_form', 'icon']
readonly_fields = ['icon']
def icon(self, obj):
if obj.eventId == 1:
icon_url = '<your_icon_url>' # get icon url
return format_html('<img src="{}">', icon_url)
return None
我需要在列表中显示 Django Admin 中的图标并根据值更改视图。
例如:
如果模型字段 eventId
具有值 1
,则显示图标(png 或 webfont)
这可能吗?
型号:
class Events(models.Model):
eventId = models.CharField(_('EventID'), max_length=254, null=False, blank=False, default='', )
name = models.CharField(_('EventName'), max_length=254, null=False, blank=False, default='', )
euuid = models.UUIDField(_('UUID'), default=uuid.uuid4, editable=False, unique=True)
created = models.DateTimeField(_('Created'), auto_now_add=True, blank=True, help_text=_('Date of the creation'))
您创建一个类似 icon() 的方法并将其添加到 list_display 字段并将其设为只读。
from django.utils.html import format_html
class EventsAdmin(admin.ModelAdmin):
...
...
list_display = ['your_list_display_fields', 'icon']
fields = ['your_model_fields_for_form', 'icon']
readonly_fields = ['icon']
def icon(self, obj):
if obj.eventId == 1:
icon_url = '<your_icon_url>' # get icon url
return format_html('<img src="{}">', icon_url)
return None