Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format Field Data Before Validation #747

Open
ThatMorneGuy opened this issue Jul 4, 2022 · 2 comments
Open

Format Field Data Before Validation #747

ThatMorneGuy opened this issue Jul 4, 2022 · 2 comments
Labels
onhold Waiting feedback

Comments

@ThatMorneGuy
Copy link

ThatMorneGuy commented Jul 4, 2022

I use a custom filter to add the currency prefix to a FloatField to make it more user friendly. This also adds the currency prefix to the value in my edit form.

from app import app

@app.template_filter()
def format_currency(value:float, currency:str=None):
    if currency == 'AUD':
        return "AU${:,.2f}".format(value)
    else:
        return "${:,.2f}".format(value)


from app._filters import format_currency

class ContractForm(Form):
    cost = FloatField('Cost', id='contract_cost', default=0.00, filters=[format_currency])

Is it possible (and how would one implement) to use a filter to remove the currency prefix from the field data on submit before form validation?

I have gone through documentation and searched forums but haven't found a solution.

@t0hi0
Copy link

t0hi0 commented Oct 21, 2022

@ThatMorneGuy, hello! You can create a custom field that inherits from FloatField and override the process_formdata method with your clear prefix logic.

@azmeuk
Copy link
Member

azmeuk commented Jul 21, 2023

If I understand correctly, the issue you are describing is that the data is validated after being transformed by filters, for instance:

>>> import wtforms
>>> def format_currency(value:float, currency:str=None):
...     return "${:,.2f}".format(value)
>>> class ContractForm(wtforms.Form):
...     cost = wtforms.FloatField(filters=[format_currency], validators=[wtforms.validators.NumberRange(1, 10)])
>>> f = ContractForm(cost=2.00)
>>> f.validate()
Traceback (most recent call last):
  File ".../validators.py", line 205, in __call__
    and not math.isnan(data)
            ^^^^^^^^^^^^^^^^
TypeError: must be real number, not str

And you would like a way to transform the data after it is being validated. Is this what you mean?

@azmeuk azmeuk added the onhold Waiting feedback label Oct 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
onhold Waiting feedback
Development

No branches or pull requests

3 participants