我正在尝试使用django imagekit为学习应用程序创建默认缩略图。我正在使用Python 3.7.4和django 3.0.4。我想创建一个脚本来预加载内容,但在我传递django ContentFile后,实例中的ProcesseImage字段为空。如何从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>
如您所见,缩略图(ProcesseImage字段)为空。当我使用admin保存一个使用同一图像时,它不是空的。如何使实例在图像完整的情况下保存?多谢各位
这会使您意识到需要将缩略图图像另存为一个单独的步骤。在上面的代码中,img是空的。如果您执行img.seek(0),则存在.jpg内容。基本上,我需要执行以下步骤:
相关问题 更多 >
编程相关推荐