trafaret icon indicating copy to clipboard operation
trafaret copied to clipboard

How to localize error messages?

Open lud4ik opened this issue 3 years ago • 2 comments

lud4ik avatar Oct 21 '21 14:10 lud4ik

hi. i think that it's not work for the trafaret. if u wanna to do localisation for an error message u can do that via a mapping of errors.

Here docs

import trafaret as t

login_validator = t.Dict({'username': t.String(max_length=10), 'email': t.Email})

try:
    login_validator.check({'username': 'So loooong name', 'email': 'misha'})
except t.DataError as e:
    errors = e.to_struct()

# {
#    'code': 'some_elements_did_not_match',
#    'nested': {
#        'username': {
#            'code': 'long_string',
#            'message': 'String is longer than 10 characters'
#        },
#        'email': {
#            'code': 'is_not_valid_email',
#            'message': 'value is not a valid email address'
#        }
#    }
# }

so with to_struct method u can to get error code and after that generate local error message

from trafaret.codes import LONG_STRING, IS_NOT_VALID_EMAIL

errors_mapper = {
    LONG_STRING: _("message is so long"),
    IS_NOT_VALID_EMAIL: _('is not valid email')
}
def trf_errors_to_local(errors):
    return {
        e: errors_mapper[errors[e]['code']]
        for e in errors
    }


trf_errors_to_local(errors['nested'])

# {'username': 'message is so long', 'email': 'is not valid emai'}

is this enough for your case? 🙂

Arfey avatar Oct 21 '21 20:10 Arfey

There is no easy way to do this now. Looks like we should implement one.

Deepwalker avatar Oct 25 '21 09:10 Deepwalker