Django:gettext和强制转换为Unicode

7

我在我的Django应用程序中有以下代码。

class Status(object):

    def __init__(self, id, desc):
        self.id = id
        self.desc = desc

    def __unicode__(self):
        return self.desc

STATUS = Status(0, _(u"Some text"))

当我尝试显示某些状态(甚至将其强制转换为Unicode)时,我会得到以下错误提示:
TypeError: coercing to Unicode: need string or buffer, __proxy__ found

请问有人能解释一下,我哪里做错了吗?

这段内容与IT技术有关。
2个回答

22
Django的_()函数可能返回一个django.utils.functional.__proxy__对象,该对象本身不是Unicode(详见http://docs.djangoproject.com/en/1.1/ref/unicode/#translated-strings)。Python不会递归调用unicode(),因此你的Status对象将__proxy__对象直接返回是错误的。你需要使__unicode__方法返回unicode(self.desc)
请注意,这只适用于Django;Python自带的gettext不会返回这些代理对象。

1
我假设@thomas-wounters已经解决了您的问题,但对于其他可能遇到类似问题的人,请检查是否没有使用ugettext_lazy
from django.utils.translation import ugettext_lazy as _

在这种情况下,您必须将输出转换为 str/unicode:
unicode(_('translate me'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接