Paul R
Paul R

Reputation: 2797

Customizing Select in Django

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.

Upvotes: 0

Views: 1990

Answers (1)

Garry Cairns
Garry Cairns

Reputation: 3115

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>

Upvotes: 2

Related Questions