0

要将原始文件替换为转换为 webp 的版本,我在models.py中执行了以下操作:

django==2.2.17
django-filer==2.0.2
Pillow==8.0.0


class Provaa(File):
    data = models.DateTimeField(auto_now=True,)

    class Meta:
        managed = True
        verbose_name = 'Allegato'

    def convert_to_webp(self):
        extension = ['jpeg', 'png', 'jpg', 'img']
        if any(ext in self.file.name.lower() for ext in extension):
            try:
                img = Image.open(self.file)
                correggi_nome = self.file.name.split('.')[0]
                img.save(correggi_nome + '.webp','webp')
                logger.error('img.save save another copy of the file not repalce the original!')

            except Exception as ex:
                logger.error(ex)


    def save(self, *args, **kwargs):
        self.convert_to_webp()
        super(Provaa, self).save()

这会正确保存 webp 文件,但在当前项目文件夹中不会替换原始文件。

ipdb> type(self.file.file)
<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
ipdb> type(self.file)
<class 'filer.fields.multistorage_file.MultiStorageFieldFile'>
ipdb> type(img)
<class 'PIL.PngImagePlugin.PngImageFile'>

我试图用 img 替换 self.file,但它失败了。我不需要保留原始文件,只保留转换后的文件。

4

1 回答 1

0

只需创建一个 DRF 序列化程序并移动在验证期间运行的模型方法。

于 2021-02-17T13:15:31.013 回答