Django 项目中的 UnicodeEncodeError

UnicodeEncodeError in Django Project

回溯:

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 并将字符集配置为 utf-8。它是来自 DigitalOcean 的默认 Django 图像。语言是俄语。我几乎尝试了类似问题的所有建议。

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

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

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