如何解决Django-filer PIL 转换并覆盖原始
要将原始文件替换为转换为 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,但它失败了。 我不需要保留原始文件,只保留转换后的文件。
解决方法
只需创建一个 DRF 序列化程序并移动验证期间运行的模型方法即可。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。