Django图像上传不上传日文命名图像

时间:2017-09-01 08:55:15

标签: python django django-models imagefield

上传日文命名图片时出现的错误是: ascii'编解码器无法编码45-48位的字符:序号不在范围内(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)

3 个答案:

答案 0 :(得分:2)

我还没有用日语测试它,但它适用于其他语言,如带有特殊字符的葡萄牙语:

在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)

答案 1 :(得分:1)

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

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

答案 2 :(得分:-1)

添加编码utf-8然后它可以接受大多数语言 还有模板html使用charset 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/