Marshmallow: Using date related fields (e.g. DateTime, Date) with allow_blank

Created on 22 Apr 2016  路  2Comments  路  Source: marshmallow-code/marshmallow

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?

question

Most helpful comment

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

All 2 comments

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
Was this page helpful?
0 / 5 - 0 ratings

Related issues

imhoffd picture imhoffd  路  3Comments

m-novikov picture m-novikov  路  3Comments

Ovyerus picture Ovyerus  路  3Comments

lassandroan picture lassandroan  路  3Comments

lupodellasleppa picture lupodellasleppa  路  3Comments