Pages

Thursday, June 29, 2017

Django Reminder Delete File when deleting object

Django Reminder Delete File when deleting object


For Django FileField objects and object of its subclasses, when using the objects delete() method, it will only delete the object record from the database, the file will remain in the appointed location in your servers filesystem.

After a few research, it is a deliberate design in Django to prevent unwanted mess in database when rolling back an record (not sure how this is doable though, leave comments if you know how :D).

So, we have to explicitly delete the file from the filesystem ourselves using

FileFieldObject.file_field.storage.delete(filepath)

A simple implementation to delete the file when delete the file object from db would be like this:

f = FileFieldObject #replace with your models .objects.get() here

storage = f.file_field.storage

#field_field is the property in your model which is an object of class model.FileField

path = f.field_field.path

storage.delete(path) #delete file from disk
f.delete() #delete record from db


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.