views:

74

answers:

2

hi using Django to create a stock photo site, i have a ImageField in my model, the problem is that when the user update the image field, the original image file isn't deleted from the hard disk.

how can I make to delete those images after an update?

Thanks!

+1  A: 

You'll have to delete the old image manually.

The absolute path to the image is stored in your_image_field.name. So you'd do something like:

os.remove(your_image_field.name)

But, as a convenience, you can use the associated FieldFile object, which gives easy access to the underlying file, as well as providing a few convenience methods. See http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield-and-fieldfile

Chris Lawlor
A: 

Hello. Use this custom save method in your model:

def save(self, *args, **kwargs):
    try:
        this = MyModelName.objects.get(id=self.id)
        if this.MyImageFieldName != self.MyImageFieldName:
            this.MyImageFieldName.delete()
    except: pass
    super(MyModelName, self).save(*args, **kwargs)

It works for me on my site. This problem was bothering me as well and I didn't want to make a cleanup script instead over good bookkeeping in the first place. Let me know if there are any problems with it.

metamemetics