David Dahan
David Dahan

Reputation: 11152

Django: how to link additional data to choices, using radio buttons?

In my projet, I'd like to create a minimalist shop page where the user can choose between items to buy. There is no data model used for this.

Simplified, the form looks like this:

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

In another file:

ORDER_CHOICES = (
    ('CARDS_100', 'Pack de 100 cartes'),
    ('CARDS_200', 'Pack de 200 cartes'),
    ('CARDS_500', 'Pack de 500 cartes'),

After that, in views.py, I will charge the user according to the choice.

However, how would you define a price to be linked to the choices? I don't want to write something ugly like this:

if form.order == 'CARDS_100':
    # charge 39€
elif form.order == 'CARDS_200':
    # charge 69€
... etc

Do you see a better alternative? Thanks a lot.

Upvotes: 1

Views: 49

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47866

You can create a ORDER_CHOICES_TO_PRICES mapping which will give you the price for a particular order choice.

ORDER_CHOICES_TO_PRICES = {
    'CARDS_100': 39,
    'CARDS_200': 69,
    ...
}  

Then in your views, you can just use this mapping to get the price.

price = ORDER_CHOICES_TO_PRICES[form.cleaned_data['order']] # will give you the price for a particular order

Upvotes: 1

Related Questions