Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get Django Admin to delete files when I remove an object from the database/model?

I am using 1.2.5 with a standard ImageField and using the built-in storage backend. Files upload fine but when I remove an entry from admin the actual file on the server does not delete.

like image 973
narkeeso Avatar asked Mar 21 '11 01:03

narkeeso


People also ask

Which method deletes the specified file in Django?

Use os.remove() function to delete File The OS module in Python provides methods to interact with the Operating System in Python. The remove () method in this module is used to remove/delete a file path.

What is admin Modeladmin in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.

What is Django cleanup?

The django-cleanup app automatically deletes files for FileField , ImageField and subclasses. When a FileField 's value is changed and the model is saved, the old file is deleted. When a model that has a FileField is deleted, the file is also deleted.


3 Answers

You can receive the pre_delete or post_delete signal (see @toto_tico's comment below) and call the delete() method on the FileField object, thus (in models.py):

class MyModel(models.Model):
    file = models.FileField()
    ...

# Receive the pre_delete signal and delete the file associated with the model instance.
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver

@receiver(pre_delete, sender=MyModel)
def mymodel_delete(sender, instance, **kwargs):
    # Pass false so FileField doesn't save the model.
    instance.file.delete(False)
like image 110
darrinm Avatar answered Oct 19 '22 17:10

darrinm


Try django-cleanup

pip install django-cleanup

settings.py

INSTALLED_APPS = (
    ...
    'django_cleanup.apps.CleanupConfig',
)
like image 55
un1t Avatar answered Oct 19 '22 16:10

un1t


Django 1.5 solution: I use post_delete for various reasons that are internal to my app.

from django.db.models.signals import post_delete
from django.dispatch import receiver

@receiver(post_delete, sender=Photo)
def photo_post_delete_handler(sender, **kwargs):
    photo = kwargs['instance']
    storage, path = photo.original_image.storage, photo.original_image.path
    storage.delete(path)

I stuck this at the bottom of the models.py file.

the original_image field is the ImageField in my Photo model.

like image 35
Kushal Avatar answered Oct 19 '22 16:10

Kushal