【问题标题】:Django ImageField error : cannot open image fileDjango ImageField 错误:无法打开图像文件
【发布时间】:2016-07-12 12:40:48
【问题描述】:

我把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)

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

【问题讨论】:

  • 您必须启用调试模式并查看实际错误是什么,或者您必须启用日志记录并使其向您发送包含错误的电子邮件。 “500 Internal Server Error”仅表示您的应用返回了错误,但无法判断是哪个错误。
  • @Tiago 感谢您的回复。调试模式已经开启,我正在尝试通过 django restf 框架使用这个图像 url。即使打开调试模式也不容易看到问题的细节。
  • 请发布完整的堆栈跟踪

标签: django model imagefield


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您在这里回复!
【解决方案2】:

让你的课程兼容 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

【讨论】:

  • docs.djangoproject.com/en/1.9/topics/files - 除了path,你还有nameurl
  • 我按照您的指示进行操作,但出现了另一个错误。错误是这样的。 >
  • 所以根据上面的结构验证你正在上传一些东西到./media/customers/photos 并且那里有一个文件 - 可能是你的文件实际上没有上传 - 如果你可以检查创建的模型实例因为它的属性。看起来像是几个问题的混合体。
  • 向我们展示您的admin.py - 它必须包含CustomerAdmin
  • 附带说明 - 将 OneOnOneField 与 Django User 一起使用比显式扩展它更好,因为它提供更简洁的设计和更简单的模型管理。
猜你喜欢
  • 2020-03-07
  • 2013-01-21
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多