Django models 如何在Django models.py中自动生成缩略图?

Django models 如何在Django models.py中自动生成缩略图?,django-models,Django Models,如果my models.py中没有现有缩略图,我会尝试自动生成缩略图。当我在管理仪表板中手动上载文件时,该方法会调整图像的大小,但如果用户尝试发布新帖子,则不会。这是my models.py: 错误:“无法将模式rgba写入jpeg” 您可以尝试将JPEG更改为PNG,然后重试 def make_thumbnail(self, image, size=(300, 200)): img = Image.open(image) img.convert('RGB') im

如果my models.py中没有现有缩略图,我会尝试自动生成缩略图。当我在管理仪表板中手动上载文件时,该方法会调整图像的大小,但如果用户尝试发布新帖子,则不会。这是my models.py:

错误:“无法将模式rgba写入jpeg”


您可以尝试将JPEG更改为PNG,然后重试

def make_thumbnail(self, image, size=(300, 200)):
     img = Image.open(image)
     img.convert('RGB')
     img.thumbnail(size)
    
     thumb_io = BytesIO()
     img.save(thumb_io, 'PNG', quality=85)
    
     thumbnail = File(thumb_io, name=image.name)
     return thumbnail
def make_thumbnail(self, image, size=(300, 200)):
     img = Image.open(image)
     img.convert('RGB')
     img.thumbnail(size)
    
     thumb_io = BytesIO()
     img.save(thumb_io, 'PNG', quality=85)
    
     thumbnail = File(thumb_io, name=image.name)
     return thumbnail