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

2

6

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.

Betulaceous answered 20/1, 2015 at 23:43 Comment(0)
F
10

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)
Frugal answered 20/1, 2015 at 23:53 Comment(1)
And what would it be for overriding the DecimalField model, in models.py?Resonance
S
0
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',)
Strow answered 12/7, 2018 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.