[Fixed]-Resizing an image only if upload_to was called django

1👍

If you just want to call os.remove only when upload_to is invoked, why not move that code inside upload_to_location function?

def upload_to_location(self, filename):
    try:
        this = Location.objects.get(id=self.id)
        if this.image_file:
            os.remove(this.image_file.path)
    except ObjectDoesNotExist:
        pass
    # do something else...

This way, when upload_to is called, os.remove will be called.

Extras

Instead of calling os.remove to delete associated file, you can delete the file by calling that file field’s delete() method.

if this.image_file:
    this.image_file.delete(save=True)

save=True saves the this instance after deleting the file. If you don’t want that, pass save=False. Default is True.

And in the function my_function2 where you’re listening to signals, it should be:

instance.image_file.path
👤xyres

Leave a comment