我正在尝试使用django-imagekit为一个学习应用程序创建默认缩略图。我使用的是Python 3.7.4和django 3.0.4。我想创建一个脚本来预加载内容,但是在我向实例中传递了django ContentFile之后,它的ProcessedImageField是空的。如何从shell添加模型实例并填充ProcessedImageField?
这是我的models.py:
from imagekit.models import ProcessedImageField
from imagekit.processors.resize import SmartResize
class MediaThumbnail(models.Model):
"""
An image that is used to visually represent and distinguish media in the
site. Implemented via django-imagekit:
https://django-imagekit.readthedocs.io/en/latest/
Attributes:
thumbnail: An image that uses imagekit processor to resize to a
standard size.
"""
thumbnail = ProcessedImageField(upload_to='resource_thumbnails',
processors=[SmartResize(185, 100)],
format='JPEG',
options={'quality': 80}
)下面是一个shell会话示例:
In [1]: from io import BytesIO
In [2]: from PIL import Image as PILImage
In [3]: path = "eduhwy/media/default_thumbnails/"
In [4]: img = PILImage.open(path + "abc.jpg")
In [5]: img
Out[5]: <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=910x607 at 0x7F49073CAC50>
In [6]: rawfile = BytesIO()
In [7]: img.save(rawfile, format='jpeg')
In [8]: from django.core.files.base import ContentFile
In [9]: django_file = ContentFile(rawfile.getvalue())
In [10]: mt = MediaThumbnail.objects.create(thumbnail=django_file)
In [11]: mt
Out[11]: <MediaThumbnail: MediaThumbnail object (724)>
In [12]: mt.thumbnail
Out[12]: <ProcessedImageFieldFile: None>正如您所看到的,缩略图(ProcessedImageField)是空的。当我使用管理员保存使用相同图像的图像时,它不是空的。如何让实例保存为完整的图像?谢谢。
发布于 2020-07-29 05:07:00
您需要将缩略图另存为一个单独的步骤。在上面的代码中,img是空的。如果执行img.seek(0),则存在.jpg内容。基本上,我需要执行以下步骤:
img = PILImage.open(path + image)
rawfile = BytesIO()
img.save(rawfile, format='jpeg')
mt = MediaThumbnail.objects.create()
mt.thumbnail.save(image, rawfile)
rawfile.close()https://stackoverflow.com/questions/63122907
复制相似问题