django特殊字符处理 [英] django special character handling
问题描述
我正在尝试了解如何正确处理Django / Python中的特殊字符。
我已经添加到我的views.py和models.py以下编码字符串:
I'm trying to understand how to deal correctly with special characters in Django / Python. I have added to my views.py and models.py the following encoding string:
# -*- coding: utf-8 -*-
但是,当以下cmd被调用时,采购订单名称设置为TestÄÜÖ它崩溃:
But when the following cmd is called with a purchase order name set to "TestÄÜÖ" it crashes:
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模型看起来像这样。
The PurchaseOrder model looks like this.
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,则不会出现此问题
在消息字符串前面:
The problem does not occur if I add u
in front of the message string:
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
。
But the docs say that in Django 1.5 (I'm using 1.5) a normal string should be a unicode string and there is no need for the u
.
所以我不想添加所有我的add_message调用一个 u
,如果文档说我不需要t
任何人都可以看出这个编码主题吗?
So I do not want to add to all my add_message calls an u
, if the docs say it is not needed.
Anybody can shed some light on this encoding topic?
推荐答案
你错过了__future__中的导入unicode_literals
将使Python2中的字符串像Python3 unicode字符串一样。
You missed the from __future__ import unicode_literals
that would make strings in Python2 act like Python3 unicode strings.
这篇关于django特殊字符处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!