<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=338168267432629&amp;ev=PageView&amp;noscript=1">
Programming

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 …


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

class Images(models.Model):
    created = models.DateField()
    image = models.FileField(upload_to=session_file_path, max_length=1000)

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.

def delete_filefield(sender, **kwargs):
    image = kwargs.get('instance')
    default_storage.delete(image.image.path)
#post delete signal
post_delete.connect(delete_filefield, 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.

Similar posts

Get notified about the latest in Tech

Be the first to know about new tech from the experts at Bixly!