I'm using WTForms (together with Flask, flask-wtf, sqlalchemy) to validate incoming JSON for REST APIs. I realize that WTForms is aimed more towards HTML form rendering and validation, but I chose it because it can autogenerate forms out of my sqlalchemy models (thanks to wtforms.ext.sqlalchemy).
Anyway, here is the problem. One of my models includes boolean field which translates to wtforms.BooleanField with DataRequired validator. The issue is that validation fails with 'This field is required' error message even if I pass correct data. My Form:
class MyForm(Form):
name = TextField('name', validators=[DataRequired()])
disabled = BooleanField('disabled', validators=[DataRequired()])
JSON data is like this:
'{"name": "John", "disabled": "false"}'
What I'm expecting:
{"disabled": "false"}-> validates successful, coerced Python data:{'disabled': False}{"disabled": "true"}-> validates successful, coerced Python data:{'disabled': True}{"disabled": ""}or'{"disabled": "foo"}'-> fails validation
Currently in first case validation is failed with {'disabled': [u'This field is required.']}
I know there is a note in docs that says DataRequired validator "require coerced data, not input data", but 1) the form is autogenerated by wtforms.ext.sqlalchemy and 2) how it is supposed to behave if I use InputRequired validator? Check (via form.validate()) that some data exists and then check that this data is "true" or "false"?
To summarize, my question is:
- What is the correct way of validating
wtforms.BooleanField? - Maybe there is some other framework that can validate incoming JSON against given sqlalchemy models?
Thanks.
default=('disabled', False)? because default value ofdisabledfield should beFalse. - mortymacsselecttag. try it:disabled = BooleanField('disabled', validators=[DataRequired()],defaults=False)- mortymacsext.sqlalchemyas your rationale for being unable to just omit the validator. Which one is it? If you have the field defined, you can just not use that validator (which is almost meaningless for a BooleanField), and otherwise, you can still override it in a subclass. - Crastmodel_formfunction fromext.sqlalchemyto generate form from sqlalchemy model. I giveMyFormdefinition here for simplicity and because it leads to same problem. Sure I can modify generated form (add/replace validators, etc) but my question was about how to generate forms I'm expecting and if that's possible at all. - Palasaty