【问题标题】:django: gettext and coercing to unicodedjango:gettext 并强制转换为 unicode
【发布时间】:2011-01-09 03:54:59
【问题描述】:

我的 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

谁能解释一下,我做错了什么?

【问题讨论】:

    标签: python django unicode gettext


    【解决方案1】:

    来自 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 不会返回这些代理对象。

    【讨论】:

    • 非常感谢,这正是我所需要的。
    【解决方案2】:

    我认为@thomas-wounters 解决了您的问题,但对于可能有类似问题的其他人 - 请检查您是否没有使用 ugettext_lazy

    from django.utils.translation import ugettext_lazy as _
    

    在这种情况下,您必须将输出转换为 str/unicode:

    unicode(_('translate me'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-30
      • 2011-11-06
      • 1970-01-01
      • 2011-11-25
      • 2011-06-12
      • 2011-01-07
      • 2020-01-21
      • 2011-10-04
      相关资源
      最近更新 更多