【问题标题】:Unicode in Django Messages FrameworkDjango 消息框架中的 Unicode
【发布时间】:2011-10-26 16:22:08
【问题描述】:

我在 Django 中有一条使用会员模型中的标准字符字段构建的 flash 消息。

messages.add_message(request,
                     messages.INFO,
                     '{0} membership created'.format(membership.name))

除非memberships.name 包含Unicode 字符,否则我会得到UnicodeEncodeError。我可以通过在字符串前面加上 u 来创建一个 unicode 字符串来解决这个问题,但我不明白为什么这是必要的,因为 Django 假设所有字节字符串都是 UTF-8 的docs 状态。我应该通过我的应用程序并将所有字符串更改为 unicode 字符串吗?

【问题讨论】:

    标签: django unicode


    【解决方案1】:

    这不是 Django 的真正问题。看起来你被 str.format 处理 unicode 参数的方式中的错误所吸引,Python Issue 7300

    一种解决方法是使用 unicode 字符串,另一种是使用% 格式。

    '%s membership created' % membership.name
    u'{0} membership created'.format(membership.name))
    

    【讨论】:

      【解决方案2】:

      是的。 除了那些实际上是字节字符串的,因为它们是从文件中读取的。

      【讨论】:

      • 或尝试“从 future 导入 unicode_literals”。当然,请阅读 Spolskys 关于 Unicode 的文章,每个人都应该阅读。
      • 我以前读过 Spolsky 的文章,但总是值得一读,谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-28
      相关资源
      最近更新 更多