WTForms: IntegerField skips coercion when string value is '0'

This question almost covers what I am here, but not quite.

It seems that IntegerField skips coercion when the string value is "0". Any other positive integer seems to work fine.

Here is an example "0":

from wtforms import validators, Form, IntegerField
from webob.multidict import MultiDict

class TestForm(Form):
    num = IntegerField('How Many?', [validators.DataRequired('num required.'), validators.NumberRange(min=0, max=100)])

data_in = {'num': '0'}  # Note '0' is a string as would be POSTed
test_form = TestForm(formdata=MultiDict(data_in))
print("HTML Render: %s" % test_form.num())
print("     Validate: %s" % test_form.validate())
print("       Errors: %s" % test_form.errors)

      

Output:

HTML Render: <input id="num" name="num" type="text" value="0">
     Validate: False
       Errors: {'num': ['num required.']}

      

And alternatively, using the '66' example:

from wtforms import validators, Form, IntegerField
from webob.multidict import MultiDict

class TestForm(Form):
    num = IntegerField('How Many?', [validators.DataRequired('num required.'), validators.NumberRange(min=0, max=100)])

data_in = {'num': '66'}  # Note '66' is a string as would be POSTed
test_form = TestForm(formdata=MultiDict(data_in))
print("HTML Render: %s" % test_form.num())
print("     Validate: %s" % test_form.validate())
print("       Errors: %s" % test_form.errors)

      

From this:

HTML Render: <input id="num" name="num" type="text" value="66">
     Validate: True
       Errors: {}

      

What gives? I could use InputRequired instead to keep it from being agnostic, but that completely defeats the purpose of this.

+3


source to share


1 answer


I'm afraid you will have to keep this type agnostic and use InputRequired instead :-)

The docs here say:

"[...] this validator used to be called Required, but the way it behaved (requiring forced data, not input) meant that it was functioning in a way that was not symmetrical to the optional validator, and also caused confusion with certain fields that coerced the data into "false" values, such as 0, decimal (0), time (0), etc. If no specific reason exists, we recommend using: class: InputRequired instead. "



The actual cuplrit code is slightly below on line 201:

if not field.data

      

+2


source







All Articles