Django-filer PIL convert and override original

152 Views Asked by At

To replace the original file with a converted to webp version I've done the follow in my 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()

This correctly save a webp file but in the current project folder not replacing the original file.

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'>

I've tried to replace the self.file with img, but it fail. I don't need to keep the original file, only the converted file.

1

There are 1 best solutions below

0
On BEST ANSWER

Just create a DRF serializer and move the model method that is run during validation.