'Django create file programatically on save

The goal with this is for the user to create an instance of the model where they populate a source URLField, and on save, it would fetch the URL and save it as a file.

class ComicImage(UUIDModel):
    src = models.URLField('Comic URL', max_length=512, blank=True)
    img = models.FileField('Images', null=True, blank=True, upload_to='comics')

    def save(self, *args, **kwargs):
        img_data = BytesIO(requests.get(self.src).content)
        self.img.save(f'{self.hash}-i.webp', content=img_data)

        super().save(*args, **kwargs)

But I keep getting an error

ValueError: The 'img' attribute has no file associated with it.

Which appears that it's not assigning a file to the field. Or rather, it doesn't until AFTER the model is saved.

Alternatively:

I also tried

self.img.save(f'{self.hash}-i.webp', content=img_data, save=True)

But it gets stuck in a loop of saving forever. If I set save=False, then it creates the model but not the file.

Is there a way to create/populate/modify the file before it's saved?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source