如何本地化WTForms验证消息?

3 投票
1 回答
1729 浏览
提问于 2025-04-17 08:07

我差不多把我的验证信息本地化成功了,你可以看到它在英语和瑞典语下都能正常工作:

英语:

这里输入图片描述

瑞典语:

这里输入图片描述

但是当我切换到葡萄牙语时,我收到了以下错误信息:

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)

我觉得我之前也遇到过这个错误信息,但我不知道该怎么处理。你能帮我吗?为什么会出现这个错误信息呢?

我的表单类的代码是

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')

我在.po文件中的翻译部分是

msgid "Name is required"
msgstr "É necessário o nome"

我的python文件是这样开始的

#!/usr/bin/python
# -*- coding: utf-8 -*-

据我所知,我已经把所有能设置的地方都设置成了unicode和utf-8。

谢谢你的帮助

1 个回答

6

如果你想在翻译中使用unicode字符,你需要用ugettext_lazy这个工具函数,而不是gettext_lazy。
这个函数名就说明了主要区别,ugettext_lazy是unicode格式的,而gettext_lazy则不是(这使得后者的用处不大)。

顺便提一下,尽可能使用unicode而不是默认字符串,也就是说,尽早把输入转换成unicode格式,尽量晚一点再把输出编码成相关的格式。

撰写回答