Login

Pre-delete signal function for deleting files a model

Author:
mindcruzer
Posted:
September 19, 2012
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

This snippit is meant to be used with the pre_delete signal to delete any files associated with a model instance before the instance is deleted. It will search the model instance for fields that are subclasses of FieldFile, and then delete the corresponding files. As such, it will work with any model field that is a subclass of FileField.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django.db.models.fields.files import FieldFile

def file_cleanup(sender, instance, *args, **kwargs):
    '''
        Deletes the file(s) associated with a model instance. The model
        is not saved after deletion of the file(s) since this is meant
        to be used with the pre_delete signal.
    '''
    for field_name, _ in instance.__dict__.iteritems():
        field = getattr(instance, field_name)
        if issubclass(field.__class__, FieldFile) and field.name:
            field.delete(save=False)

...

from django.db import models
from django.db.models.signals import pre_delete

class SomeModel(models.Model):
    ...
    my_file = models.FileField(upload_to='my_files')
    ...

# delete my_file when we delete an instance of SomeModel
pre_delete.connect(file_cleanup, sender=SomeModel)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

un1t (on March 17, 2015):

There is special app for that django-cleanup

pip install django-cleanup

settings.py

INSTALLED_APPS = (
    ...
    'django_cleanup', # should go after your apps
)

#

Please login first before commenting.