Is there a way to display the color of a (hex color) field in the Django Admin site?

Viewed 1775

I have a model in Django 3:

class Ingredient(models.Model):
    name_EN = models.CharField(max_length=100, unique=True, null=True)
    hexcolor = models.CharField(max_length=7, default="#ffffff")

    def __str__(self):
        return self.name_EN

This lists Ingredients and has associated a name with it, e.g. 'Dill' or 'Tomato', and a 'hexcolor' e.g. #C5E1A5 or #DD2C00. Currently, from the admin site, I can see the ingredients listed as name_EN of the Ingredient, and when I click through also the hexcolor value (#......). But I would like to see the actual color listed next to the name_EN, so I can see it (and change when needed). It doesn't necessarily need a color picker, could be nice, but I seek in the first place how to display the color (e.g. the background color of the hexcolor field?).

Any suggestions where and how to do this? Would be appreciated.

1 Answers

As described in Django3 documentation, you can do this by using a method like colored_name method as below:

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

class Ingredient(models.Model):

    name_EN = models.CharField(max_length=100, unique=True, null=True)
    hexcolor = models.CharField(max_length=7, default="#ffffff")

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


class IngredientAdmin(admin.ModelAdmin):
    list_display = ('name_EN', 'hexcolor', 'colored_name')
Related