我的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
有人能解释我,我做错了吗?
答案 0 :(得分:22)
Django的_()
函数可以返回一个django.utils.functional.__proxy__
对象,它本身不是unicode(参见http://docs.djangoproject.com/en/1.1/ref/unicode/#translated-strings)。 Python不会递归调用unicode()
,因此Status对象直接返回__proxy__
对象是错误的。您需要制作__unicode__
方法return unicode(self.desc)
。
请注意,这是Django特有的; Python自己的gettext
不会返回这些代理对象。
答案 1 :(得分:1)
我认为@ thomas-wounters解决了您的问题,但对于可能遇到类似问题的其他人 - 请检查您是否使用ugettext_lazy
:
from django.utils.translation import ugettext_lazy as _
在这种情况下,您必须将输出转换为str / unicode:
unicode(_('translate me'))