2

When I upload an image through Django administrator and I delete the image file again, why does it not delete the image int the /media directory?

When I delete an image file, I want it to delete the image automatically even from the directory, not only the model instance.

My model:

class ImageForExtractText(models.Model):
    image = models.FileField()

And settings:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")

What should I do to make it happen, when deleting the image file from Django administration? It should be deleted from both Django administration and the media directory.

Geekfish
  • 2,173
  • 23
  • 28
  • There is already a similar question here, with many answers: https://stackoverflow.com/questions/21941503/django-delete-unused-media-files – Geekfish Mar 22 '19 at 15:58

1 Answers1

3

Django doesn't delete the files on delete.

You can add a signal to delete the file:

from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver

class ImageForExtractText(models.Model):
    image = models.FileField()

@receiver(pre_delete, sender=ImageForExtractText)
def delete_image(sender, instance, **kwargs):
    # Pass false so FileField doesn't save the model.
    if instance.image:
        instance.image.delete(False)
Navid Zarepak
  • 4,148
  • 1
  • 12
  • 26