当我尝试通过默认的 instance.file_field.save 方法将名称中带有俄语符号的文件添加到模型实例时,我从存储后端收到一个 UnicodeDecodeError(ascii 解码错误,不在范围 (128) 内(堆栈跟踪在 os.save 上结束)。存在。如果我通过默认的python文件打开/写入这个文件,一切正常。所有文件名都在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)')
最佳答案
解决方法很简单:
在修订版 12659 中,此错误已修复。
http://code.djangoproject.com/ticket/11030
但修订版 12661 将其还原
“(在 [12661] 中)修复了 #11030:恢复了假设文件系统编码为 utf8 的更改,并更改了测试以演示该假设如何损坏不使用 utf8 作为文件的系统上上传的非 ASCII 文件名系统编码(特别是 Windows)。感谢 vrehak 的报告。”
所以我需要做的就是恢复到 12659
关于django - UnicodeDecodeError 尝试通过 django 默认基于文件的后端保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2457087/