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.
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.
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.
Most helpful comment
https://marshmallow.readthedocs.io/en/3.0/api_reference.html#marshmallow.fields.Field.default_error_messages
I'm not sure this is exactly how
Field.default_error_messagesis 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.