Marshmallow: Changing the default error messages in marshmallow3

Created on 11 Feb 2019  ·  2Comments  ·  Source: marshmallow-code/marshmallow

Hi. Thanks for the great library! It has been really helpful.

I had a quick question. Currently, the default error message for required is set to "Missing data for required field". This error message does not fit my use case for any of the fields however and I have to keep passing the following error_messages dictionary to every field where I need to change the error message.
Example:

error_messages = {"required": "My custom required message"}

required_field1 = String(required=True, error_messages=error_messages)
required_field2 = Email(required=True, error_messages=error_messages)

Is there a better way to do this to reduce code repetition? For example, is there a Meta class variable or something similar that I can change in order to change the default error messages for all marshmallow fields?

Thanks for your time in advance.

question

Most helpful comment

https://marshmallow.readthedocs.io/en/3.0/api_reference.html#marshmallow.fields.Field.default_error_messages

from marshmallow import fields

Field.default_error_messages["required"] = "My custom required message"

I'm not sure this is exactly how Field.default_error_messages is intended to be used, but as long as you modify it before any field instances are created, your custom messages will be used for all fields.

All 2 comments

You could subclass all fields:

from marshmallow import fields

class String(fields.String):
    default_error_messages = {"required": "My custom required message"}

You could even use a Mixin to reduce duplication across fields.

class CustomErrorMessagesMixin:
    default_error_messages = {"required": "My custom required message"}

class String(fields.String, CustomErrorMessagesMixin):
    """Custom message String field"""

class Int(fields.Int, CustomErrorMessagesMixin):
    """Custom message Int field"""

Just my 2 cents. Maybe someone will come up with a better way.

https://marshmallow.readthedocs.io/en/3.0/api_reference.html#marshmallow.fields.Field.default_error_messages

from marshmallow import fields

Field.default_error_messages["required"] = "My custom required message"

I'm not sure this is exactly how Field.default_error_messages is intended to be used, but as long as you modify it before any field instances are created, your custom messages will be used for all fields.

Was this page helpful?
0 / 5 - 0 ratings