Use the more descriptive name in Django choices

Viewed 60

I am creating an eCommerce app and have come into a problem where I can't seem to make Django display the 2nd item in the tuple. For example, my models.py...

class ProductItem(models.Model):
    OPTIONS = [
        ("RED","Red"),
        ("DBL","Dark Blue"),
        ("LBL","Light Blue"),
        ("DGR","Dark Green"),
        ("LGR","Light Green"),
        ("PNK","Pink"),
        ("GRY","Gray"),
        ("BLK","Black"),
        ("BRO","Brown"),
        ("WHT","White"),
        ("MAR","Marroon"),
        ("ORG","Orange"),
        ("BEG","Beige"),
        ("GLD","Gold"),
        ("SLV","Silver"),
        ("MLT", "MultiColour")
    ]
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    colour = models.CharField(choices=OPTIONS, default="BLK", max_length=20)
    quantity_available = models.PositiveIntegerField()

    def __str__(self):
        return f"{self.product} -> ({self.colour})"

And in my views.py...

def product_detail(request, id):
    products = Product.objects.filter(id=id).first()
    context={
        "product": products, 
        "options": ProductItem.objects.filter(product=products)
    }
    return render(request, "store/product_detail.html", context)

And finally in my template...

<select id="style">
   {% for option in options %}
        <option value="{{option.colour}}">{{option.colour]}}</option>
   {% endfor %}
</select>

In this case, let's assume that the Dark Blue Colour should appear. I want the value to be DBL as I have mentioned in the CHOICES and want the Dark Blue to be displayed for the user. But in this case, only DBL is shown, something that I don't want. Any idea on how to tackle this?

Thanks!

1 Answers

You can work with the get_fieldname_display() method [Django-doc]. so for the colour field, that is get_colour_display():

<select id="style">
    {% for option in options %}
        <option value="{{ option.colour }}">{{ option.get_colour_display }}</option>
    {% endfor %}
</select>
Related