Django 图片上传不上传日语命名图片

Django image upload not uploading japanese named image

我在上传日文命名图片时遇到的错误是:ascii' codec can't encode characters in position 45-48: ordinal not in range(128)

图片以英文字符命名时可以完美上传。另外,奇怪的是,我遇到的错误只是在我将其上传到服务器时才出现。日语命名不会在部署服务器上上传,但在开发中运行良好。

我的模特:

class Tenant_Post(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
    name = models.CharField(max_length=255,null=True)
    image = models.FileField(upload_to='image/tenant/',null=True)
    posted_on = models.DateTimeField(auto_now_add=True, auto_now=False)
    last_modified_on = models.DateTimeField(auto_now_add=False, 
    auto_now=True)

    def __unicode__(self):
        return self.name

我的看法:

@login_required(login_url='/')
def new(request):
    if request.method == 'POST':
        print request.POST
        form = TenantForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            print 'success'
            return HttpResponseRedirect(reverse('tenant:all'))
        else:
            print 'fail'
            return render(request,'tenant/new.html',{'form':form,})
    else:
        form = TenantForm()
        return render(request,'tenant/new.html',{'form':form,})

完整的追溯在这里:

File "/opt/python/run/venv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/opt/python/run/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/opt/python/run/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/opt/python/run/venv/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/opt/python/current/app/tenant/views.py" in edit
  64.                 instance.save()

File "/opt/python/run/venv/lib/python2.7/site-packages/django/db/models/base.py" in save
  806.                        force_update=force_update, update_fields=update_fields)

File "/opt/python/run/venv/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  836.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/opt/python/run/venv/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  900.                       for f in non_pks]

File "/opt/python/run/venv/lib/python2.7/site-packages/django/db/models/fields/files.py" in pre_save
  296.             file.save(file.name, file.file, save=False)

File "/opt/python/run/venv/lib/python2.7/site-packages/django/db/models/fields/files.py" in save
  94.         self.name = self.storage.save(name, content, max_length=self.field.max_length)

File "/opt/python/run/venv/lib/python2.7/site-packages/django/core/files/storage.py" in save
  53.         name = self.get_available_name(name, max_length=max_length)

File "/opt/python/run/venv/lib/python2.7/site-packages/django/core/files/storage.py" in get_available_name
  77.         while self.exists(name) or (max_length and len(name) > max_length):

File "/opt/python/run/venv/lib/python2.7/site-packages/django/core/files/storage.py" in exists
  392.         return os.path.exists(self.path(name))

File "/opt/python/run/baselinenv/lib64/python2.7/genericpath.py" in exists
  26.         os.stat(path)

Exception Type: UnicodeEncodeError at /tenant/edit/4/
Exception Value: 'ascii' codec can't encode characters in position 45-48: ordinal not in range(128)

添加编码utf-8然后它可以接受大多数语言 也对模板 html 使用字符集 utf-8

# -*- coding: UTF-8 -*- in at the top the file

<meta charset="utf-8"/> in html templates

编辑: 请阅读官方文档或添加此行

 from __future__ import unicode_literals

https://docs.djangoproject.com/en/1.11/ref/unicode/

我没有用日语测试它,但它可以与其他一些语言一起使用,比如带有特殊字符的葡萄牙语:

将此添加到您的 settings.py

DEFAULT_FILE_STORAGE = 'app.models.ASCIIFileSystemStorage'

还有你的app.models.ASCIIFileSystemStorage

# This Python file uses the following encoding: utf-8
from django.db import models
from django.core.files.storage import FileSystemStorage
import unicodedata

class ASCIIFileSystemStorage(FileSystemStorage):
    """
    Convert unicode characters in name to ASCII characters.
    """
    def get_valid_name(self, name):
        name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore')
        return super(ASCIIFileSystemStorage, self).get_valid_name(name)

您的错误是由 os.stat(path) 调用引发的,这意味着您的文件系统不支持日文字符(实际上它可能只支持 ascii 或某些 latin-xxx 或 windows-yyy 编码).

这里你主要有两个解决方案:将你的系统配置为在任何地方都使用 utf-8(无论如何这是 IMVHO 做的明智的事情),或者确保你只使用你的系统编码(或只是简单的 ascii)文件系统名称等(参见 leeeandroo 的回答)。