在 Django 表单中处理优雅降级
我有一个类似于以下内容的表单(为简洁起见进行了简化):
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 中创建一个函数来计算并返回正确的值?
或者也许有人可以建议一种更干净的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为类型选择定义自定义小部件并包含 JavaScript 代码 作为单独的 .js 文件。
Define a custom widget for the type selection and include the JavaScript code as a separate .js file.