How to localize my WTForms validation message?
-
13-03-2021 - |
Вопрос
I nearly got my validation message localized as you can see it works for English and Swedish:
English:
Swedish:
But when I switch to Portuguese I get the following error message:
Traceback (most recent call last):
File "/media/Lexar/montao/lib/webapp2/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/media/Lexar/montao/montaoproject/main.py", line 1749, in post
current_user=self.current_user,
File "/media/Lexar/montao/montaoproject/main.py", line 466, in render_jinja
self.response.out.write(template.render(data))
File "/media/Lexar/montao/montaoproject/jinja2/environment.py", line 894, in render
return self.environment.handle_exception(exc_info, True)
File "/media/Lexar/montao/montaoproject/templates/insert_jinja.html", line 249, in top-level template code
<ul class="errors">{% for error in form.name.errors %}<li>{{ error }}</li>{% endfor %}</ul>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
I think I've had this error message before and I don't know how to handle it. Could you please help me? Why does this error message appear?
The code for my form class is
class AdForm(Form):
my_choices = [('1', _('VEHICLES')), ('2', _('Cars')), ('3', _('Bicycles'))]
name = TextField(_('Name'), [validators.Length(min=4, max=50,
message=_(u'Name is required') )])
title = TextField(_('title'), [validators.Required()])
text = TextAreaField(_('Text'), widget=TextArea())
phonenumber = TextField(_('Phone number'))
phoneview = BooleanField(_('Display phone number on site'))
price = TextField(_('Price'))
password = PasswordField(_('Password'))
email = TextField(_('Email'))
category = SelectField(choices = my_choices, default = '1')
The translation part in my .po file is
msgid "Name is required"
msgstr "É necessário o nome"
My python file begins like this
#!/usr/bin/python
# -*- coding: utf-8 -*-
And AFAIK I've set everything I can to unicode and utf-8.
Thank you for the help
Решение
If you want to be able to use unicode characters in your translations, you need to use the ugettext_lazy utility function and not gettext_lazy.
The main difference, as the function name hints, is that ugettext_lazy is unicode when gettext_lazy is not (which makes it not that useful by the way).
While you're at it, you could / should use unicode instead of default strings whenever possible, that is, convert input to unicode ASAP, and encode output as late as possible to the relevant encoding.