简体   繁体   中英

How to accept both dot and comma as a decimal separator with WTForms?

I'm using WTForms to display and validate form input. I use a DecimalField for a money amount input, which works fine when inserting a value with a dot as a decimal separator. Since this website will be used in continental Europe however, I also want to allow a comma as a decimal separator. This means that both "2.5" and "2,5" should result in a value meaning "two and a half".

When I input a value with a comma, I get an error saying 'Not a valid decimal value' . How can I accept both dots and commas as decimal separators with WTForms?


I know I can use Babel to use locale-based number formatting, but I don't want that. I specifically want to accept both a dot and a comma as separator values.

You can subclass DecimalField and replace commas with periods before the data is processed:

class FlexibleDecimalField(fields.DecimalField):

    def process_formdata(self, valuelist):
        if valuelist:
            valuelist[0] = valuelist[0].replace(",", ".")
        return super(FlexibleDecimalField, self).process_formdata(valuelist)
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',)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM