【问题标题】:Django encoding problems with path name路径名的 Django 编码问题
【发布时间】:2016-07-05 19:04:15
【问题描述】:

我正在做一个 Django 项目,它需要非 ascii 字符,如 àéã 等。到目前为止,我已经能够很好地导航这个编码地狱,但我在上传文件的路径名方面遇到了问题。

我有一个这样的模型:

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' codec can't encode character u'\xe1' in position 7: ordinal not in range(128) 。如果我改为强制编码:

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

我收到以下错误:IOError: [Errno 2] No such file or directory: 'C:\Django_project\Storage\Property\Bras\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 在顶部有 # -*- coding: utf-8 -*-,并导入了 unicode_literals。

【问题讨论】:

  • 那个问题是关于路径名中的正斜杠和反斜杠的问题 - 我的问题是关于编码的。不同的主题。

标签: python django encoding utf-8


【解决方案1】:

使用 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))    

【讨论】:

  • 谢谢!由于环境原因,我无法在我的项目中对此进行测试,但我在另一个项目中对其进行了测试,并且似乎工作得很好。
猜你喜欢
  • 1970-01-01
  • 2021-08-28
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-14
相关资源
最近更新 更多