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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With