当我尝试通过默认的instance.file_field.save方法将名称中包含俄语符号的文件添加到模型实例时,我得到一个UnicodeDecodeError(ascii解码错误,不在存储后端的范围(128)内(stacktrace结束)在os.exist上。如果我通过默认的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)')
答案 0 :(得分:4)
解决方案非常简单:
在修订版12659中,此错误已得到修复。 http://code.djangoproject.com/ticket/11030
但修订版12661将其还原
“(在[12661]中)已修复#11030:恢复了假定文件系统编码为utf8的更改,并更改了测试以演示该假设如何在不使用utf8的系统上损坏上载的非ASCII文件名作为他们的文件系统编码(特别是Windows)。感谢vrehak的报告。“
所以我需要做的就是恢复到12659
答案 1 :(得分:0)
我怀疑这只是确保upload_to
属性是unicode的问题:
file = models.FileField(null=True, blank=True, max_length = 300,
upload_to=u'articles_files/%Y/%m/%d/')