当使用“清除”复选框删除上传的图像并在 Django 管理界面中单击“保存”时,我得到以下结果:
TypeError at /admin/foo/bar/1/
coercing to Unicode: need string or buffer, ImageFieldFile found
Exception Value: coercing to Unicode: need string or buffer, ImageFieldFile found Exception Location: /home/ec2-user/ve/Project/lib/python2.6/site-packages/django/core/files/images.py in get_image_dimensions, line 47
我知道这可能与返回的 unicode 类型有关,因此在相关 中已从
代码但这并没有解决问题。这是调试日志:return image
更改为 return image.name
ImageField
/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 方法的导入如下: 从 django.core.files.images 导入 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
最佳答案
The signature for function 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
希望这有帮助!
关于python - 从管理界面删除 ImageField 时出现 Django unicode 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17364160/