David Dahan
David Dahan

Reputation: 11162

Django: How to customize a form ChoiceField display?

I'm creating a minimalist shop with Django.

class CardOrderForm(forms.Form):
    order = forms.ChoiceField(
        label="",
        choices=ORDER_CHOICES,
        widget=forms.RadioSelect)

ORDER_CHOICES = (
    ('CARDS_100_G', 'Pack de 100 cartes génériques'),
    ('CARDS_200_G', 'Pack de 200 cartes génériques'),
    ('CARDS_500_G', 'Pack de 500 cartes génériques'))

Then, I created an object to map prices to order choices:

ORDER_PRICES = {
    # Without/With TAXES
    'CARDS_100_G': (39, 46.80),
    'CARDS_200_G': (69, 82.80),
    'CARDS_500_G': (149, 178.80))}

Currently, in my template, I have {{ form.order }} which displays a raw list of 3 choices like this:

However, I can't find a way to customize this display to be able to add the price next to the item. I'd like to have this result:

Any idea? Thanks.

Upvotes: 1

Views: 658

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599580

You can create a new set of choices dynamically.

ORDER_CHOICES_WITH_PRICES = [
    (key, "%s - %s€" % (val, ORDER_PRICES[key][0]))
    for key, val in ORDER_CHOICES
]

Upvotes: 1

Related Questions