Django ImageField error : cannot open image file

Django ImageField error : cannot open image file

我将ImageField放入Model中,可以成功上传图片文件。但是当尝试通过管理页面打开文件时。无法打开文件,但出现“500 内部服务器错误”错误。

文件名中有一些非ascii字母。我该如何解决这个问题?

class Customer(User):
    profile_image = models.ImageField(upload_to='customers/photos', null=True, blank=True)
    hospital = models.ForeignKey('Hospital', null=True, blank=True)
    treatments = models.ManyToManyField('Treatment', blank=True)
    verified = models.BooleanField(default=False)

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email


image file name = "데이비드_베컴2.jpg"

其实这个模型不止一个字段..

+) admin.py

class CustomerAdmin(UserAdmin):
    form = CustomerChangeForm
    add_form = CustomerCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'phonenumber', 'is_admin')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password', 'phonenumber', 'smscheck',
                  'name', 'hospital', 'major', 'treatments', 'info', 'profile_image', 'verified', )}),
        ('Personal info', {'fields': ()}),
        ('Permissions', {'fields': ('is_active', 'is_admin',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2', 'phonenumber', 'smscheck',
                  'name', 'hospital', 'major', 'treatments', 'info', 'verified', 'is_active', 'is_admin')}
        ),
    )
    search_fields = ('email', 'phonenumber')
    ordering = ('email',)
    filter_horizontal = ()

同样,当我把文件用英文编码时,它也没有问题.. 例如,"myprofile.jpg"

+) 详细错误

Traceback (most recent call last):
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/whitenoise/base.py", line 57, in __call__
    static_file = self.find_file(environ['PATH_INFO'])
  File "/usr/local/lib/python2.7/site-packages/whitenoise/django.py", line 72, in find_file
    if self.use_finders and url.startswith(self.static_prefix):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xeb in position 22: ordinal not in range(128)

我该如何解决这个问题?提前致谢!

使您的 class 与 unicode 兼容。

from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible 
class Customer(User):
    profile_image = models.ImageField(upload_to='customers/photos', null=True, blank=True)

    def __str__(self):
        return self.profile_image.path

    def __unicode__(self):
        return unicode(self.profile_image.path)

此外,请确保您的媒体目录已在 settings.py:

中定义
MEDIA_ROOT = './media/'
MEDIA_URL = '/media/'

确保您的 LANG 环境变量已设置 - 使用您的语言环境

export LANG="en_US.UTF-8"

还添加导出到 ~/.bashrc

我终于找到了这个错误的解决方案。

只需为自己实施新的自定义字段。

import unicodedata
from django.db.models import ImageField

class MyImageField(ImageField):

    def __init__(self, *args, **kwargs):
        super(MyImageField, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):
        data = super(MyImageField, self).clean(*args, **kwargs)
        data.name = unicodedata.normalize('NFKD', data.name).encode('ascii', 'ignore')
        return data

有关此的更多信息,您可以查看 here