I have a Model with an image field and I want to be able to change the image using a ModelForm. When changing the image, the old image should be deleted and replaced by the new image.
I have tried to do this in the clean method of the ModelForm like this:
def clean(self):
cleaned_data = super(ModelForm, self).clean()
old_profile_image = self.instance.image
if old_profile_image:
old_profile_image.delete(save=False)
return cleaned_data
This works fine unless the file indicated by the user is not correct (for example if its not an image), which result in the image being deleted without any new images being saved. I would like to know where is the best place to delete the old image? By this I mean where can I be sure that the new image is correct before deleting the old one?
Edit:
I prefer to do this in my ModelForm class if possible.
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:
Now I can easily add the above functionality to a ModelForm with an image field by inheriting from ChangeImageForm like this:
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.