我试图了解如何正确处理 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))
但是文档说,在 Django 1.5(我使用的是 1.5)中,普通字符串应该是 unicode 字符串,不需要u
.
u
因此,如果文档说不需要,我不想添加到我所有的 add_message 调用中。任何人都可以对这个编码主题有所了解吗?