python - Django 如何判断上传的图片是否有效?

标签 python django python-imaging-library

我正在尝试将图像添加到我的 Django 应用程序中的模型。

模型.py

class ImageMain(models.Model):
"""This is the Main Image of the product"""
    product = models.ForeignKey(Product)
    photo = models.ImageField(upload_to='products')

在开发模式下,每次我尝试通过 Django admin 上传图片时,我都会收到:

Upload a valid image. The file you uploaded was either not an image or a corrupted image.

我尝试上传的 jpg 可以用 os X 预览查看,所以它似乎是有效的。

问题似乎是 Python 图像库无法将其识别为图像。为什么有效图像会发生这种情况?

PIL 已安装,并通过 Django shell 验证。

最佳答案

根据 Django 的源代码。这三行负责验证图像:

from PIL import Image
trial_image = Image.open(file)
trial_image.verify()

PIL 可能不支持图像类型。检查支持的格式列表 here

关于python - Django 如何判断上传的图片是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1368724/

相关文章:

python - django dumpdata 空数组

Mac 上的 Python 和 Django : Illegal hardware instruction

python - 如何在Python中加载Matlab的结构体(用v7.3保存)

django - request.POST.getlist 在 Django 中返回 None 列表?

database - Django - 设计模型关系 - 管理界面和内联

python - 使用 PIL 在终端中显示图像 (png)

python - 打印 1-100 的数字,跳过可被 3 和 5 整除的数字

python 记录 : How to replace the output file of a FileHandler?

python - 文件未找到错误: [Errno 2] No such file or directory: 'frame0.png' but actually has

python-imaging-library - PIL Python中的仿射变换