0

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.

Josh Scholl
  • 143
  • 15
Paul R
  • 2,631
  • 3
  • 38
  • 72
  • 2
    What is your purpose in doing this? If you want to style the form, you should use css. Background-color variable you are supplying is also invalid. – Nick Tomlin Oct 23 '13 at 13:22
  • I want visual color choice instead of simple. How CSS will help if each option has different background? – Paul R Oct 23 '13 at 13:30
  • Are you trying to create a select with an image or swatch displayed next to the option text? – Brandon Taylor Oct 23 '13 at 14:02
  • I don't want to select with image. I just want to set background of option based on value from db. – Paul R Oct 23 '13 at 14:12

1 Answers1

2

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>
Garry Cairns
  • 3,005
  • 1
  • 18
  • 33