Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to localize error messages? #119

Open
lud4ik opened this issue Oct 21, 2021 · 2 comments
Open

How to localize error messages? #119

lud4ik opened this issue Oct 21, 2021 · 2 comments

Comments

@lud4ik
Copy link
Contributor

lud4ik commented Oct 21, 2021

No description provided.

@Arfey
Copy link
Collaborator

Arfey commented Oct 21, 2021

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? 🙂

@Deepwalker
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants