尝试通过django默认基于文件的后端保存文件的UnicodeDecodeError

Iva*_*sov 6 django unicode django-models

当我尝试通过默认的instance.file_field.save方法将名称中包含俄语符号的文件添加到模型实例时,我得到一个UnicodeDecodeError(ascii解码错误,不在存储后端的范围(128)中(堆栈跟踪在os上结束).如果我通过默认的python文件写这个文件open/write all right.所有文件名都在utf-8.我只在测试Gentoo时得到这个错误,在我的Ubuntu工作站上一切正常.

class Article(models.Model):
    file = models.FileField(null=True, blank=True, max_length = 300,
                            upload_to='articles_files/%Y/%m/%d/')

Traceback:
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
  100.                     response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  24.                 return view_func(request, *args, **kwargs)
File "/var/www/localhost/help/wiki/views.py" in edit_article
  338.                 new_article.file.save(fp, fi, save=True)
File "/usr/lib/python2.6/site-packages/django/db/models/fields/files.py" in save
  92.         self.name = self.storage.save(name, content)
File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in save
  47.         name = self.get_available_name(name)
File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in get_available_name
  73.         while self.exists(name):
File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in exists
  196.         return os.path.exists(self.path(name))
File "/usr/lib/python2.6/genericpath.py" in exists
  18.         st = os.stat(path)

Exception Type: UnicodeEncodeError at /edit/
Exception Value: ('ascii', u'/var/www/localhost/help/i/articles_files/2010/03/17/\u041f\u0440\u0438\u0432\u0435\u0442', 52, 58, 'ordinal not in range(128)')
Run Code Online (Sandbox Code Playgroud)

Iva*_*sov 4

解决方案非常简单:

在修订版 12659 中,此错误已得到修复。 http://code.djangoproject.com/ticket/11030

但修订版 12661 恢复了它

“(在 [12661] 中)修复了#11030:恢复了假设文件系统编码为 utf8 的更改,并更改了测试以演示该假设如何在不使用 utf8 作为文件的系统上损坏上传的非 ASCII 文件名系统编码(特别是 Windows)。感谢 vrehak 的报告。”

所以我需要做的就是恢复到12659

  • 事实上,您需要在 Apache 中设置适当的环境:http://code.djangoproject.com/ticket/11030#comment:5 (3认同)