fabiocaccamo / django-colorfield

:art: color field for django models with a nice color-picker in the admin.
MIT License
632 stars 95 forks source link

Show the color in the `change_list` view (currently only shows the hex value) #91

Open titarch opened 2 years ago

titarch commented 2 years ago

I am using django-colorfield in one of my project, it's awesome but I needed a way to get a list overview of the color to make sure they don't clash to much with one another.

So instead of displaying the hex value, it would be great to have a similar colored badge (except without the picker) as the creating/editing admin views.

As a temporary workaround, I am just coloring the background of the list view to the color using an extended admin template like so:

{% extends "admin/change_list.html" %}

{% block extrahead %}
    {{ block.super }}
    <script>
        function getTextColor(backgroundColor) {
            const color = (backgroundColor.charAt(0) === '#') ? backgroundColor.substring(1, 7) : backgroundColor;
            const r = parseInt(color.substring(0, 2), 16); // hexToR
            const g = parseInt(color.substring(2, 4), 16); // hexToG
            const b = parseInt(color.substring(4, 6), 16); // hexToB
            const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
            return (yiq >= 128) ? 'black' : 'white';
        }

        document.addEventListener("DOMContentLoaded", function (event) {
            const color_td = document.querySelectorAll("td.field-color");
            color_td.forEach(function (td) {
                const color = td.innerText;
                td.style.backgroundColor = color;
                td.style.color = getTextColor(color);
            });
        });
    </script>
{% endblock %}

which looks like this: image

I was thinking maybe this would be a feature others would be interested in, though I don't know how easy it would to make generic and configurable in the project. Other than this, going from setting the background color to a nice colored badge is not such a big leap.

If you are interested I can look more into the code base and see if I can implement it and submit a PR.

Fund with Polar

fabiocaccamo commented 2 years ago

@titarch True, this is useful. It can be achieved without using js at all.

titarch commented 2 years ago

That's great then, it makes things easier (I think). I'll see if I can figure that out in the next few days