2016-07-05 70 views
0

我在做一個Django項目,期望非ascii字符,比如àéã等等。到目前爲止,我已經能夠很好地瀏覽這個編碼地獄,但是我遇到了路徑名的問題上傳的文件。Django的路徑名編碼問題

我有一個模型,上面寫着這樣的:

class Property (models.Model): 
    #... 
    city = models.CharField(max_length = 100, choices = CITIES_LIST) 
    pdf_file = models.FileField(upload_to = generateUploadPath) 

的upload_to調用創建的路徑來存儲文件的功能的基礎上,市域(這是可以有非ASCII字符領域):

def generateUploadPath (instance, file): 
    city = instance.city 
    storage_path = r'Property\{city}\{file}'.format(city = city, file = file) 
    return storage_path 

這很好。如果文件夾不存在,則使用正確的名稱創建文件夾,並將文件正確存儲在那裏。問題是,我有一個post_save信號讀取所述文件並以特定方式處理它:

@receiver(signals.post_save, sender = Property) 
def fileProcessing (sender, instance, created, **kwargs): 

    file_path = instance.pdf_file.path 
    pdf_file = open(file_path, 'r') 

這裏是代碼中斷的地方。如果這樣做,運行一個窗體會彈出以下錯誤:UnicodeEncodeError'ascii'編解碼器無法編碼字符u'\ xe1'在位置7:序號不在範圍內(128)。如果我,相反,強制與編碼:

file_path = instance.pdf_file.path.encode('utf-8') 

我收到以下錯誤:IO錯誤[錯誤2]沒有這樣的文件或目錄:「C:\ Django_project \存儲\地產\文胸\ xc3 \ xadlia \ test_file.pdf',即使該文件夾在Windows中正確創建爲'.. \ Property \Brasília\'。

整個項目是UTF-8,我使用Python 2.7.11,Django 1.9.4,db是Postgres 9.5,數據庫編碼也設置爲UTF-8。我的models.py# - * - 編碼:utf-8 - * -在頂部,導入unicode_literals。

+0

這個問題是關於一個問題與路徑名向前和向後斜槓 - 礦約爲編碼。不同的主題。 –

回答

0

使用python_2_unicode_compatible裝飾:

from django.utils.encoding import python_2_unicode_compatible, force_text 

@python_2_unicode_compatible 
class Property (models.Model): 
    #... 
    city = models.CharField(max_length = 100, choices = CITIES_LIST) 
    pdf_file = models.FileField(upload_to = generateUploadPath) 

    def __str__(self): 
     return force_text(self.pdf_file.path) 

    def __unicode__(self): 
     return force_text(unicode(self.pdf_file.path)) 

    def get_file_path(self): 
     return force_text(unicode(self.pdf_file.path))  
+0

謝謝!由於情況,我無法在我的項目中對此進行測試,但我在另一個項目中對其進行了測試,似乎工作得很好。 –