Pre-delete signal function for deleting files a model

 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. Render markdown to a separate model field by mindcruzer 8 months ago
  2. FileField / ImageField with a delete checkbox by tomZ 5 years, 6 months ago
  3. Unique naming for file uploads by mindcruzer 8 months ago
  4. REMOVE IMAGEFIELD ATTACHMENT IN DJANGO by timonweb 1 year ago
  5. Updated FileField / ImageField with a delete checkbox by tomZ 5 years, 2 months ago

Comments

(Forgotten your password?)