I have a form that looks similar to the following (simplified for brevity):
PRICING_PATTERN = r'(?:^\$?(?P<flat_price>\d+|\d?\.\d\d)$)|(?:^(?P<percent_off>\d+)\s*\%\s*off$)'
class ItemForm(forms.Form):
pricing = forms.RegexField(
label='Pricing',
regex=PRICING_PATTERN
)
pricing_type = forms.CharField(
label='Deal type',
widget=forms.RadioSelect(
choices=(
('flat_price','Flat price'),
('percent_off','Percentage off'),
),
attrs={'style': 'display: none;'})
),
)
pricing_flat_price = forms.DecimalField(
label='Flat price',
max_digits=5,
decimal_places=2,
widget=forms.TextInput(attrs={'style': 'display: none;'})
)
pricing_percent_off = forms.IntegerField(
label='Percent off',
required=False,
min_value=0,
max_value=100,
widget=forms.TextInput(attrs={'style': 'display: none;'})
)
Initially, for the purpose of graceful degradation, only pricing is visible. If the user has javascript enabled, I hide pricing and make pricing_type visible. Now, on a pricing_type radio selection, I make either pricing_flat_cost or pricing_percent_off visible. This makes for a more precise and user-friendly UI.
My questions: How should I go about coding the logic that figures out where to take the values from---the RegexField or the pricing_flat_price and pricing_percent_off fields? Should I perhaps create a function in ItemForm that figures it out and returns the correct value?
Or perhaps there's a cleaner approach that someone could suggest?