我有一个类似于以下的表单(为简洁起见进行了简化):
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;'})
)
最初,出于优雅降级的目的,只有定价是可见的。如果用户启用了 javascript,我会隐藏 pricing 并使 pricing_type 可见。现在,在 pricing_type 单选选项中,我使 pricing_flat_cost 或 pricing_percent_off 可见。这使得用户界面更加精确和用户友好。
我的问题:我应该如何编写逻辑来确定从何处获取值——RegexField 或 pricing_flat_price 和 pricing_percent_off 字段?我是否应该在 ItemForm 中创建一个函数来计算并返回正确的值?
或者有人可以建议更简洁的方法?
请您参考如下方法:
为类型选择定义自定义小部件并包含 JavaScript 代码 as a separate .js file .
