python - 如何本地化我的 WTForms 验证消息?

标签 python unicode localization gettext wtforms

我几乎将我的验证消息本地化了,你可以看到它适用于英语和瑞典语:

英语:

enter image description here

瑞典语:

enter image description here

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

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。

谢谢你的帮助

最佳答案

如果你想在你的翻译中使用 unicode 字符,你需要使用 ugettext_lazy 实用函数而不是 gettext_lazy。
正如函数名称所暗示的那样,主要区别在于 ugettext_lazy 是 unicode 而 gettext_lazy 不是(顺便说一句,这使得它没那么有用)。

当你这样做时,你可以/应该尽可能使用 unicode 而不是默认字符串,也就是说,尽快将输入转换为 unicode,并尽可能晚地将输出编码为相关编码。

关于python - 如何本地化我的 WTForms 验证消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8458634/

相关文章:

ios - 在 iOS 中未显示隐私警报的本地化文本

python - 在 Pandas 数据框中使用多个参数 'apply'

python - 如何在 Pandas 数据框中反转 .astype(str)?

python - 如何在python中读取unicode文件(不是UTF-8)

python - Django 是否对 Unicode (utf-8?) 字符串进行双重编码?

c# - Silverlight 应用程序中的字符串本地化问题

.net - 我如何从 .Net 文化中获取 Sql 语言名称

java - 为什么 Java 和 Python 的垃圾回收方法不同?

python - Python 中 unicode 的问题

javascript - unicode 规范化文件输入字符串