How to setup automatic deletion of files referenced by a filefield after record is deleted. Django 1.3

In Django 1.3 deleting a record of a filefield will not automatically delete the file associated with the record. This is done to prevent data loss scenarios such as roll back transactions and different models representing the same file. So to clean up unrepresented files in the database, you have to do a manual cleanup of the files by making a management script.

In this short tutorial, I will show you how to automatically delete referenced files. However, you should be careful in applying this method to your application because as stated above, you may encounter problems when you delete files that are also referenced somewhere else in your project.

Take note that there are many other ways to automatically delete referenced files (such as overriding the delete method ), but in this tutorial we’ll use a custom method attached to a post_delete signal.

So here’s how to do it, for instance you have:

models.py

If you’re not familiar about signals, I suggest that you read the Signals documentation (https://docs.djangoproject.com/en/dev/topics/signals/)

In the next step we’ll create a delete method for the file in the storage backend and attach it to a post_delete signal of the class Images.

All done! With this method on your models.py, every time you successfully delete an Image object the delete_filefield file will be called. Furthermore, you can also add another method to delete the previous file referenced by the filefield by using a post_save signal.