处理django形式的优雅降解
-
29-09-2019 - |
题
我的表格看起来与以下相似(简化为简单):
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_type 可见的。现在,在 pricing_type 无线电选择,我要做 pricing_flat_cost 或者 pricing_percent_off 可见的。这使得更精确,用户友好。
我的问题:我应该如何编码逻辑,该逻辑从何处从何处获取价值--- pricing_flat_price 和 pricing_percent_off 字段?我应该在 itemform 弄清楚并返回正确的值?
也许有人可以建议一种更清洁的方法?
解决方案
为类型选择定义自定义小部件,并包括JavaScript代码 作为单独的.js文件.
不隶属于 StackOverflow