我的 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
谁能解释一下,我做错了什么?
最佳答案
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
不会返回这些代理对象。
关于python - django:gettext 和强制转换为 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2133508/