【问题标题】:How to accept both dot and comma as a decimal separator with WTForms?如何接受点和逗号作为 WTForms 的小数分隔符?
【发布时间】:2015-03-19 09:13:13
【问题描述】:

我使用WTForms 来显示和验证表单输入。我使用DecimalField 输入金额,在插入带有点作为小数点分隔符的值时效果很好。然而,由于该网站将在欧洲大陆使用,我希望允许逗号作为小数分隔符。这意味着 both "2.5" 和 "2,5" 应该产生一个意思是“两个半”的值。

当我输入带逗号的值时,我收到错误消息'Not a valid decimal value'。如何在 WTForms 中同时接受点和逗号作为小数分隔符?


我知道我可以使用 Babel 来使用基于区域设置的数字格式,但我不希望这样。我特别想接受点和逗号作为分隔符值。

【问题讨论】:

    标签: python decimal wtforms


    【解决方案1】:

    您可以在处理数据之前将DecimalField 子类化并用句点替换逗号:

    class FlexibleDecimalField(fields.DecimalField):
    
        def process_formdata(self, valuelist):
            if valuelist:
                valuelist[0] = valuelist[0].replace(",", ".")
            return super(FlexibleDecimalField, self).process_formdata(valuelist)
    

    【讨论】:

    • 在 models.py 中重写 DecimalField 模型是什么?
    【解决方案2】:
    class FlexibleDecimalField(forms.DecimalField):
    
        def to_python(self, value):
            # check decimal symbol
            comma_index = 0
            dot_index = 0
            try:
                comma_index = value.index(',')
            except ValueError:
                pass
            try:
                dot_index = value.index('.')
            except ValueError:
                pass
            if value:
                if comma_index > dot_index:
                    value = value.replace('.', '').replace(',', '.')
            return super(FlexibleDecimalField, self).to_python(value)
    
    class FooForm(forms.ModelForm):
        discount_value = FlexibleDecimalField(decimal_places=2, max_digits=8)
    
        class Meta:
            model = Foo
            fields = ('discount_value',)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多