1

当使用清除复选框删除上传的图像并单击 Django 管理界面中的保存时,我得到以下结果:

/admin/foo/bar/1/ 处的类型错误

强制转换为 Unicode:需要字符串或缓冲区,找到 ImageFieldFile

异常值:强制转换为 Unicode:需要字符串或缓冲区,找到 ImageFieldFile 异常位置:/home/ec2-user/ve/Project/lib/python2.6/site-packages/django/core/files/images.py in get_image_dimensions,第 47 行

我知道这可能与返回的 unicode 类型有关,因此在相关代码中已从 更改return image为,但这并没有解决问题。这是调试日志:return image.nameImageField

/home/user/ve/Project/lib/python2.6/site-packages/django/db/transaction.py
in inner
              return func(*args, **kwargs) ...

/home/user/ve/Project/lib/python2.6/site-packages/django/contrib/admin/options.py
in change_view
          if form.is_valid(): ...

/home/user/ve/Project/lib/python2.6/site-packages/django/forms/forms.py
in is_valid
      return self.is_bound and not bool(self.errors) ...

/home/user/ve/Project/lib/python2.6/site-packages/django/forms/forms.py
in _get_errors
          self.full_clean() ...

/home/user/ve/Project/lib/python2.6/site-packages/django/forms/forms.py
in full_clean
      self._clean_fields() ...

/home/user/ve/Project/lib/python2.6/site-packages/django/forms/forms.py
in _clean_fields
                  value = field.clean(value, initial) ...

/home/user/Devel/Project/project-cms/project/forms.py in clean
      w, h = get_image_dimensions(image) ...

/home/user/ve/Project/lib/python2.6/site-packages/django/core/files/images.py
in get_image_dimensions
      file = open(file_or_path, 'rb') ...

get_image_dimensions 方法是这样导入的: from django.core.files.images import get_image_dimensions

这是 clean 函数的主体:

def clean(self, value, initial=None):
    image = super(TheImageField, self).clean(value, initial)
    if image is None: return
    w, h = get_image_dimensions(image)
    if w != TheImageField.required_width or h != TheImageField.required_height:
        error_message = self.error_messages['incorrect_size'] % (w,h,)
        raise util.ValidationError(error_message)
    return image
4

1 回答 1

1

函数的签名get_image_dimensions是这样的:

def get_image_dimensions(file_or_path, close=False)

file_or_path应该是磁盘中文件的字符串,而不是ImageField,因此出现错误。

你可以这样做:

def clean(self, value, initial=None):
    image = super(TheImageField, self).clean(value, initial)
    if image is None: return
    # this is where I changed the code to add image.path
    w, h = get_image_dimensions(image.path)
    if w != TheImageField.required_width or h != TheImageField.required_height:
        error_message = self.error_messages['incorrect_size'] % (w,h,)
        raise util.ValidationError(error_message)
    return image

希望这可以帮助!

于 2013-06-28T13:40:30.713 回答