Вопрос

I have the following model

class Color(models.Model):
    """
    Colors
    """
    name = models.CharField(max_length=50, db_column="name", unique=True)
    hex = models.CharField(max_length=6, db_column="hex", unique=True)

This model is foreignkey for some other model, so represented as dropdown list. I want to modify this list so it looks like

<select>
<option style="background-color:#hex1">name1</option>
<option style="background-color:#hex2">name2</option>
</select>

I know that django already does this, except the styling. I also know that I need to extend select Widget and override render_option method, but I don't know how to pass hex values to new widget. How can I d this?

Thank you.

Это было полезно?

Решение

Unless I misunderstand the question you can just use basic django templates. Let's say you're passing the QuerySet of colours as colours, then you'd use:

<select>
{% for colour in colours %}
<option style="background-color:#{{ colour.hex }}">{{ colour.name }}</option>
{% endfor %}
</select>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top