[Django]-Where to delete model image?

0👍

Ok I figured out how to do it in a clean way using a ModelForm. Basically I create a class called ‘ChangeImageForm’, which will make sure to delete the old image when changing an image. Furthermore it also works if an image is invalid:

class ChangeImageForm(ModelForm):

    def clean(self):
        cleaned_data = super(ModelForm, self).clean()
        self.old_image = self.instance.image
        return cleaned_data

    def save(self, commit=True):
        instance = super(ChangeImageForm, self).save(commit)

        if self.old_image:
            self.old_image.delete(save=False)

        return instance

Now I can easily add the above functionality to a ModelForm with an image field by inheriting from ChangeImageForm like this:

class MyModelForm(ChangeImageForm):
    class Meta:
        model = MyModel # model with an image field

I think overriding the ModelForm is the best place to do this, instead of in the Model class, since I only want to delete the old image in some cases.

👤WesDec

0👍

Some answers:

An ImageField should validate that the uploaded file is an image via the Python Imaging Library. If it is not, the form will not validate.

Your ImageField should have a path to the old file in its path attribute.

You can delete the old image after you save the new one. Better, don’t ever use the user’s filename input as a filename. That’s safer, and you can just use the same filename — then you just overwrite the old file each time and can drop the delete step.

Good luck.

👤Erik

Leave a comment