django:gettext 并强制转换为 unicode
我的 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
有人可以解释一下,我做错了什么吗?
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"))
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
Could anyone explain me, what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Django 的
_()
函数可以返回一个django.utils.function.__proxy__
对象,该对象本身不是 unicode (请参阅 http://docs.djangoproject.com/en/1.1/ref/unicode/#translated-strings )。 Python 不会递归调用unicode()
,因此 Status 对象直接返回__proxy__
对象是错误的。您需要使__unicode__
方法返回 unicode(self.desc)
。请注意,这是 Django 特有的; Python 自己的
gettext
不会返回这些代理对象。The
_()
function from Django can return adjango.utils.functional.__proxy__
object, which is itself not unicode (see http://docs.djangoproject.com/en/1.1/ref/unicode/#translated-strings). Python does not callunicode()
recursively, so it's an error for your Status object to return the__proxy__
object directly. You need to make the__unicode__
methodreturn unicode(self.desc)
.Note that this is specific to Django; Python's own
gettext
doesn't return these proxy objects.我假设 @thomas-wounters 解决了您的问题,但对于可能有类似问题的其他人 - 请检查您是否没有使用
ugettext_lazy
:在这种情况下,您必须将输出转换为 str/unicode:
I assume that @thomas-wounters solved your issue, but for others who might have a similar issue - please check if you are not using
ugettext_lazy
:in that case, you must cast output to str/unicode: