简体   繁体   中英

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:

  • Pack de 100 cartes génériques
  • Pack de 200 cartes génériques
  • Pack de 500 cartes génériques

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:

  • Pack de 100 cartes génériques - 39€
  • Pack de 200 cartes génériques - 69€
  • Pack de 500 cartes génériques - 149€

Any idea? Thanks.

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
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM