2011-12-10 32 views
3

我几乎得到了我的验证消息本地化,你可以看到它适用于英语和瑞典语:如何本地化我的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上了。

感谢您的帮助

+1

你的别名是什么? –

+0

谢谢你的提问。我的'_'是'from'django.utils.translation import gettext_lazy as _'所以我使用的翻译函数来自django。 –

+1

该错误是由于使用默认的ASCII编码来解码字符串而导致其他编码转换为Unicode。什么编码是你的Python源文件和po文件保存在?你的po文件中设置了什么_Content-Type和_Content-Transfer-Encoding_?你有没有在你的python源文件中设置默认编码: #!/ usr/bin/env python #encoding:utf-8 –

回答

6

如果你希望能够在您的翻译使用Unicode字符,你需要使用ugettext_lazy效用函数,而不是gettext_lazy。
作为函数名称提示的主要区别是,当gettext_lazy不是(这使得它不那么有用)时,ugettext_lazy是unicode。

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

+0

谢谢托马斯。这真的有帮助。 –