2011-07-02 46 views
21

我對unicode的本質有點模糊不清,但我不確定所有的部分如何組合在一起。在管理頁面中顯示特定實例時出現錯誤。管理頁面上的django unicode錯誤

Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode character u'\u2019' in position 29: ordinal not in range(128)

這裏是我的模型:

class Proposal(models.Model): 
    project = models.ForeignKey(Project) 
    dateCreated = models.DateTimeField(editable=False) 
    xml = models.TextField(max_length=1000000) 

    def __str__(self): 
     return str('Proposal for: %s' % self.project.name) 

我已經到我的MySQL數據庫和驗證數據庫,表和列都整理爲utf8_unicode_ci,所以我不明白爲什麼頁面正在嘗試呈現ascii。查看各種論壇和文檔,我看到提及的strunicode函數,但它們似乎沒有任何關係,因爲實例列表在管理頁面顯示正常。它只是顯示導致問題的實際實例表單。

下面是一些示例XML我從phpMyAdmin的拉...

<?xml version="1.0" encoding="UTF-8"?> 
<proposal> 

    <section title="OVERVIEW"> 
    <section title="Introduction"> 
     <text> 
    This proposal is not in the system because it was completed as an agreement in Word previous to us getting this application up and running. Please refer to the attachments in this project for documentation or to see the agreement. 
     </text> 
    </section> 
    </section> 
</proposal> 

我甚至試過刻意排除XML(我不能從長遠來看,這樣做,因爲我想它喜歡可以在管理部分編輯),但我仍然得到相同的錯誤,所以我甚至不相信xml甚至是問題。如果xml不是問題,我不知道還有什麼可以保持這個頁面不被顯示。

class ProposalAdmin(admin.ModelAdmin): 
    exclude = ('xml',) 
admin.site.register(Project) 

回答

38

有一個字符的地方,可能是在self.project.name。如果你檢查整個錯誤信息,你可能會發現它。

但是,如果你正從你的數據庫統一的結果,很可能會更加聰明,能做到這樣的事情:

def __str__(self): 
    return ('Proposal for: %s' % self.project.name).encode('ascii', errors='replace') 

聰明的事,因爲它是recommended by the Django documentation,是貫徹落實__unicode__函數:

def __unicode__(self): 
    return u'Proposal for: %s' % self.project.name 
+1

Thanks for the encode()trick - ps:it should'encode('ascii','replace')' –

+0

@Yuji Tomita,我想你可以兩種方式調用它。關鍵字參數和東西:http://docs.python.org/reference/expressions.html#calls –

+2

'編碼()'沒有關鍵字參數 - 至少在2.6 –

6

2019是RIGHT SINGLE QUOTATION MARK,通常用作捲曲撇號。

問題可能是由你使用__str__,而不是__unicode__Django's documentation建議您只使用__unicode__

實例列表可能顯示正常,因爲它不包含包含撇號的字段。

+0

爲'__unicode__'建議增加了10億次!我花了3小時查看原因,爲什麼我在管理員詳細信息視圖中收到錯誤。 __unicode__覆蓋爲我修復了它。 –

5

(我想補充這是安德烈的註釋,但沒有50分還)

此:

def __unicode__(self): 
    return 'Proposal for: %s' % self.project.name 

應該

def __unicode__(self): 
    return u'Proposal for: %s' % self.project.name 

,這是特別如果您在定義中使用變量,則返回true,如果引用另一個可能返回字符串unicode的字符串不喜歡的變量。在返回的文本前加上「u」,確保所有內容都是猶太教版本,並以unicode形式返回。