django:gettext和胁迫到unicode [英] django: gettext and coercing to unicode
问题描述
我的django应用程序中有以下代码。
I have following code in my django application.
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)时,我得到:
When I try to display some status (or even coerce it to unicode), I get:
TypeError: coercing to Unicode: need string or buffer, __proxy__ found
有没有人可以解释我,我做错了什么? p>
Could anyone explain me, what I am doing wrong?
推荐答案
Django的 _()
函数可以返回一个 django.utils.functional .__代理__
对象,它本身不是unicode(参见 http://docs.djangoproject.com/en/1.1/ref/unicode/#translated-strings )。 Python不递归调用 unicode()
,所以Status对象直接返回 __ proxy __
对象是一个错误。您需要使 __ unicode __
方法 return unicode(self.desc)
。
The _()
function from Django can return a django.utils.functional.__proxy__
object, which is itself not unicode (see http://docs.djangoproject.com/en/1.1/ref/unicode/#translated-strings). Python does not call unicode()
recursively, so it's an error for your Status object to return the __proxy__
object directly. You need to make the __unicode__
method return unicode(self.desc)
.
请注意,这是特定于Django的; Python自己的 gettext
不返回这些代理对象。
Note that this is specific to Django; Python's own gettext
doesn't return these proxy objects.
这篇关于django:gettext和胁迫到unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!