Django项目中的UnicodeEncodeError

时间:2015-08-28 09:23:48

标签: django encoding digital-ocean

回溯:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "/home/django/upgrademystartup/project/views.py" in create_or_edit_project
  130.             prj.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
  710.                        force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
  738.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in _save_table
  800.                       for f in non_pks]
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in pre_save
  315.             file.save(file.name, file, save=False)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in save
  94.             self.name = self.storage.save(name, content, max_length=self.field.max_length)
File "/usr/local/lib/python2.7/dist-packages/django/core/files/storage.py" in save
  54.             name = self.get_available_name(name, max_length=max_length)
File "/usr/local/lib/python2.7/dist-packages/django/core/files/storage.py" in get_available_name
  90.         while self.exists(name) or (max_length and len(name) > max_length):
File "/usr/local/lib/python2.7/dist-packages/django/core/files/storage.py" in exists
  295.         return os.path.exists(self.path(name))
File "/usr/lib/python2.7/genericpath.py" in exists
  18.         os.stat(path)

Exception Type: UnicodeEncodeError at /project/edit/8
Exception Value: 'ascii' codec can't encode characters in position 61-66: ordinal not in range(128)

wsgi.py:

import os
import sys

from django.core.wsgi import get_wsgi_application

reload(sys)
sys.setdefaultencoding("utf-8")

os.environ['LANG'] = 'en_US.UTF-8'
os.environ['LC_ALL'] = 'en_US.UTF-8'

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "upgrademystartup.settings")

application = get_wsgi_application()

语言环境页面是:

getlocale: (None, None)
getdefaultlocale(): ('en_US', 'UTF-8')
fs_encoding: ANSI_X3.4-1968
sys default encoding: utf-8

因为我正在使用gunicorn。服务器是 nginx ,并将charset配置为utf-8。它是DigitalOcean的默认Django图像。语言是俄语。我几乎尝试了类似问题的每一条建议。

1 个答案:

答案 0 :(得分:1)

编辑wsgi.py是错误的方法,因为在启动Django应用程序之前需要设置 LANG LC_ALL 变量。

对于DigitalOcean Django图像,您应该打开gunicorn Upstart脚本/etc/gunicorn.d/gunicorn.p并在开始应用之前添加两个变量:

env LANG = en_US.UTF-8
env LC_AL = en_US.UTF-8