Marshmallow: Why aren't custom error_messages supported for the `load` and `loads` methods on Schema?

Created on 10 Sep 2019  路  7Comments  路  Source: marshmallow-code/marshmallow

Title.

Why does this code only support dump and dumps?

Validation happens on load and loads too, so presumably it makes sense for me to able to overload those messages with the same class variable too, no?

docs question

All 7 comments

Validation happens on load and loads too

No, it doesn't.

@lafrech I might be confused, but then what is the meaning of this? Is that not Schema validation on load and loads?

I'm the one who was confused. Validation happens on load and not on dump. (Validation on dump is a recurrent question, hence my confusion. Sorry about that.)

I think the doc is wrong. It should read load instead of dump.

Summary:

  • Validation and error_messages are only for load.
  • We need to fix the docs.

Thanks for pointing this out.

Gotcha, no worries.

I'm afraid I'm still stuck though. I'm using flask-marshmallow for my Schemas, and the error messages are not changing when I add an error_messages class variable. This is on load.

For reference, my code is this:

class UserLoginSchema(ma.Schema):
    email = ma.String(required=True)
    password = ma.String(required=True)
    error_messages = {
        "required": "input required",
    }

Originally I was trying to do this in a BaseSchema I've created (to overload the error_messages in all my Schemas) but that wasn't working in for some reason, and neither is specifying it directly in this derived class as shown in the docs. Can you confirm that you are able to overload the error_messages using this class variable method?

I thought it could somehow be the fact that I'm using flask-marshmallow, but it didn't work when I tried deriving my schema from marshmallow.Schema directly either.

Really though I want to be able to do it in a base class using SchemaOpts + OPTIONS_CLASS.

@acnebs

"Required" validation is field-level, not schema-level, so you need to set the default error messages on Field.

from marshmallow import Schema, fields

fields.Field.default_error_messages["required"] = "boom!"


class ArtistSchema(Schema):
    name = fields.Str(required=True)


print(ArtistSchema().validate({}))  # {'name': ['boom!']}

@lafrech The docs appear correct. Am I missing something?

This part:

https://marshmallow.readthedocs.io/en/latest/extending.html#custom-error-messages

You can customize the error messages that dump and dumps uses when raising a ValidationError. You do this by overriding the error_messages class variable:

Should read load/loads.

Ah thanks. Fixed

Was this page helpful?
0 / 5 - 0 ratings

Related issues

k0nsta picture k0nsta  路  4Comments

pd-Shah picture pd-Shah  路  4Comments

imhoffd picture imhoffd  路  3Comments

jayennis22 picture jayennis22  路  4Comments

sloria picture sloria  路  3Comments