Where to delete model image?

Posted by WesDec on Stack Overflow See other posts from Stack Overflow or by WesDec
Published on 2012-07-10T20:27:31Z Indexed on 2012/07/10 21:15 UTC
Read the original article Hit count: 410

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?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models