Looks like I can't provide allow_blank as a parameter to fields.DateTime or similar to pass validation when I pass an empty string. Is this possible?
You cannot pass allow_blank to DateTime. You can, however, pass allow_none=True and ensure that empty strings get translated into None using a pre_load method.
from marshmallow import Schema, fields, pre_load
class MySchema(Schema):
foo = fields.DateTime(allow_none=True)
@pre_load
def translate_empty_strings(self, data):
data['foo'] = data.get('foo') or None
return data
sch = MySchema(strict=True)
assert sch.load({'foo': ''}).errors == {}
For anyone stumbling on this useful bit of code, functions wrapped with @pre_load get passed other args than data too (e.g. many). So to prevent an error like
TypeError: translate_empty_strings() got an unexpected keyword argument 'many'
change the function signature to
class MySchema(Schema):
foo = fields.DateTime(allow_none=True)
@pre_load
def translate_empty_strings(self, data, *args, **kwargs):
data['foo'] = data.get('foo') or None
return data
Most helpful comment
For anyone stumbling on this useful bit of code, functions wrapped with
@pre_loadget passed other args than data too (e.g. many). So to prevent an error likechange the function signature to