2013-06-11 128 views
0

我想了解如何與在Django/Python的特殊字符正確對待。 我已經加入到我的views.py和models.py中以下編碼字符串:Django的特殊字符處理

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

但當下面的CMD調用與設置爲「TestÄÜÖ」採購訂單名稱崩潰:

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,如果文檔說是不需要的。 任何人都可以揭示出這個編碼話題一些輕?

+0

試一下'purchase_order.encode('utf-8')' –

回答

2

你錯過了from __future__ import unicode_literals這將使在Python2行爲像Python3 unicode字符串的字符串。

+0

謝謝!錯過了在文檔中:( –