django在apache中上传中文文件名报错的解决方案filefield,imagefield
问题是这样的,如果是django的测试服务器,问题不会出现。如果用apache,上传一个中文名的文件,就会报一个500错误。具体的异常点来自storage,反应的是unicode编码错误。
UnicodeEncodeError: 'ascii' codec can't encode characters in position 52-54: ordinal not in range(128)
File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/fields/files.py", line 92, in save
self.name = self.storage.save(name, content)
File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/files/storage.py", line 48, in save
name = self.get_available_name(name)
File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/files/storage.py", line 74, in get_available_name
while self.exists(name):
File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/files/storage.py", line 218, in exists
return os.path.exists(self.path(name))
File "/srv/.virtualenvs/letebo/lib/python2.6/genericpath.py", line 18, in exists
st = os.stat(path)
在网上查,有些说这是apache环境变量设置的问题。apache默认的LANG设置为C,只要把它设置为utf-8就行了。试了一下,还是不行。真是百思不得其解。后来看到一篇说在nginx上运行django的类似问题http://serverfault.com/questions/359934/unicodeencodeerror-when-uploading-files-in-django-admin。有人提出需要用locale-gen生成一下所需的locale。一试OK了。
看看文档上说,locale文件比较大,一个就50M。所以安装时是不会自动把locale全生成了,而是在需要的时候才用locale-gen[centos 是localedef]生成。
比如我们要在apache上用zh_CN.UTF-8。【http.conf中加入 setEnv LANG zh_CN.UTF-8】
那就要用locale-gen zh_CN.UTF-8生成一下就OK了。 centos是: localedef
也可以这样:
locale-gen zh_CN.UTF-8
当django部署到apache上时,有时候发现中文附件名没办法上传,解决办法
vi /etc/apache2/envvars
最后添加
export LANG='zh_CN.UTF-8'
export LC_ALL='zh_CN.UTF-8'
关闭文件
locale-gen zh_CN.UTF-8
重启apache即可