Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WTForms BooleanField treats JSON false value as true

I'm using wtforms to handle data from my post requests. One certain post requests sends a variety of data including a boolean value.

My form looks like this:

class EditFileForm(Form):
    title = StringField('title')
    shared = BooleanField('shared')
    fileID = IntegerField('fileID')
    userID = IntegerField('userID')

I can see that when I receive the request the data looks like this:

data = MultiDict(mapping=request.json)
print(data)
>>MultiDict([(u'shared', False), (u'title', u'File5'), (u'userID', 1), (u'fileID', 16)])

You can see the boolean field is "false", and printing the raw data shows that too However, when I print the actual form field I get true.

print(form.shared.raw_data)
[False]
print(form.shared.data)
True

I read that WTForms might not know how to handle false boolean values. What is the proper way of doing this? Using an IntegerField instead?

I have another form with a booleanfield that is handling false boolean values from my postgres database just fine.

like image 525
Brosef Avatar asked Jun 29 '16 01:06

Brosef


1 Answers

WTForms is not really meant to work with JSON data. In this case, BooleanField checks that the value it received is in field.false_values, which defaults to ('false', ''). The False object is not in there, so it's considered true.

You can pass a different set of false_values to the field.

BooleanField(false_values={False, 'false', ''})

Or patch it for all instances by placing this somewhere before the field is used for the first time.

BooleanField.false_values = {False, 'false', ''}

You may better off using a serialization library such as Marshmallow to handle JSON data.

like image 84
davidism Avatar answered Sep 20 '22 00:09

davidism