【问题标题】:django special character handlingdjango 特殊字符处理
【发布时间】:2013-06-11 16:50:02
【问题描述】:

我试图了解如何正确处理 Django / Python 中的特殊字符。 我在 views.py 和 models.py 中添加了以下编码字符串:

# -*- coding: utf-8 -*-

但是,当使用设置为“TestÄÜÖ”的采购订单名称调用以下 cmd 时,它会崩溃:

messages.add_message(request, messages.INFO, 'The purchase order "%s" has been successfully added to project "%s".' % (purchase_order, project.name))

抛出的错误如下:

File "..accounting/views.py", line 1100, in post_logic
    messages.add_message(request, messages.INFO, 'The purchase order "%s" has been successfully added to project "%s".' % (purchase_order, project.name))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 20: ordinal not in range(128)

PurchaseOrder 模型如下所示。

class PurchaseOrder(models.Model):
    """
    purchase order assigned to a project
    """

    number = models.CharField(max_length=200)
    name = models.CharField(max_length=200, null=True, blank=True, default="")

    def __unicode__(self):
        return u'%s - %s' % (self.name, self.number)

如果我在消息字符串前面添加u,则不会出现问题:

messages.add_message(request, messages.INFO, u'The purchase order "%s" has been successfully added to project "%s".' % (purchase_order, project.name))

但是docs 说在 Django 1.5(我使用的是 1.5)中,普通字符串应该是 unicode 字符串,不需要u

因此,如果文档说不需要,我不想在我的所有 add_message 调用中添加u。 任何人都可以对这个编码主题有所了解吗?

【问题讨论】:

  • 试试purchase_order.encode('utf-8')

标签: python django encoding


【解决方案1】:

您错过了from __future__ import unicode_literals,它会使 Python2 中的字符串表现得像 Python3 unicode 字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2019-10-13
    相关资源
    最近更新 更多