gpt4 book ai didi

python - 在 Django 表单中处理优雅降级

转载 作者:太空宇宙 更新时间:2023-11-04 06:30:06 24 4
gpt4 key购买 nike

我有一个类似于以下的表单(为简洁起见进行了简化):

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_costpricing_percent_off 可见。这使得用户界面更加精确和用户友好。

我的问题:我应该如何编写逻辑来确定从何处获取值——RegexField 或 pricing_flat_pricepricing_percent_off 字段?我是否应该在 ItemForm 中创建一个函数来计算并返回正确的值?

或者有人可以建议更简洁的方法?

最佳答案

为类型选择定义自定义小部件并包含 JavaScript 代码 as a separate .js file .

关于python - 在 Django 表单中处理优雅降级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3909564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com