django特殊字符处理

时间:2013-06-11 16:50:03

标签: python django encoding

我正在尝试理解如何正确处理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

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

1 个答案:

答案 0 :(得分:2)

你错过了from __future__ import unicode_literals,它会使Python2中的字符串像Python3 unicode字符串一样。