News, ideas and randomness

Don’t delete an image file when deleting a Django model instance

Posted: March 2nd, 2010 | Author: Scott Barnham | Filed under: Django | Tags: | 1 Comment »

If you have a Django model with a FileField or ImageField, when you delete the model instance, the associated file or image is also deleted. In most cases this is desirable and keeps things tidy, but I had a situation recently where the image file should not be deleted when the model was deleted. Here’s a simple way to override the default behaviour.

Custom file storage

Django uses storage classes to determine how files are read and written. Normally, the data is just written as files to disk, but there are other possibilities such as storing on remote servers.

It’s easy to write a custom file storage class to override the behaviour of the default FileStorageSystem. In this case, we only need to change the delete method so it does not delete the file.


from django.core.files import storage

class NoDeleteFileStorage(storage.FileSystemStorage):
    def delete(self, name):

We can then use the custom file storage by making an instance and passing it to the ImageField.


from custom import NoDeleteFileStorage

ndfs = NoDeleteFileStorage()

class ImageInstance(models.Model):
    image = models.ImageField(storage=ndfs, ...)

It’s as simple as that! Custom file storage has some interesting possibilities. With it you can handle how files are named or integrate with some caching or CDN.