首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django-filer PIL转换和重写原始

Django-filer PIL转换和重写原始
EN

Stack Overflow用户
提问于 2021-02-11 16:17:16
回答 1查看 65关注 0票数 0

为了用转换成webp版本的文件替换原始文件,我在我的models.py中做了如下操作

代码语言:javascript
复制
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文件,但在当前的项目文件夹中不会替换原始文件。

代码语言:javascript
复制
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,但失败了。我不需要保留原始文件,只需要转换文件。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-17 13:15:31

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66158497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档