2016-07-05 75 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

谢谢!由于情况,我无法在我的项目中对此进行测试,但我在另一个项目中对其进行了测试,似乎工作得很好。 –