15

I've got a model Picture with an ImageField. When deleting an instance of Picture, the file set in the ImageField is not deleted.

Is it a bug? How can I do it?

jul
  • 36,404
  • 64
  • 191
  • 318
  • What does your view look like? – rh0dium Jul 12 '12 at 16:38
  • possible duplicate of [How do I get Django Admin to delete files when I remove an object from the database/model?](http://stackoverflow.com/questions/5372934/how-do-i-get-django-admin-to-delete-files-when-i-remove-an-object-from-the-datab) – Chris Pratt Jul 12 '12 at 16:49

2 Answers2

32

Deletion of files associated with FileFields and ImageFields was intentionally removed in Django 1.3. See ticket #6456. Django uses transactions extensively to prevent data corruption if something goes wrong with the request. If a deletion transaction is rolled-backed, after the file has been deleted from the filesystem, then you now have a record pointing to a non-existent file. All tickets asking for automatic deletion to return have been summarily marked "Won't Fix", so this is not going to change.

For workarounds, see this previous StackOverflow question.

Community
  • 1
  • 1
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
1

The assumptions?

class Picture(models.Model):
    image = ImageField(blank=True, null=True, upload_to="pics")

    def delete(self, *args, **kwargs):
        self.image.delete()
        super(Picture, self).delete(*args, **kwargs)

Then lets manually create and delete this..

image = "./image.jpg"
picture = Picture.objects.create(image=File(open(image, "r"))
picture.save()

Then delete it?

picture.delete()

HTH

lipka
  • 1,162
  • 11
  • 19
rh0dium
  • 6,811
  • 4
  • 46
  • 79
  • 5
    Although this answer is already quite old: line 5 in the first codeblock should be `self.image.delete()` – Tim Oct 17 '14 at 11:25
  • 2
    And it better use signals as it doesn't work for `Picture.objects.filter(...).delete()` for example. – Sassan Sep 10 '16 at 08:38