ImageField: overwrite file if file with the same name exists

Sep 29, 2013 · Updated: Jul 12, 2021 · by Tim Kamanin

Create a separate file

from import FileSystemStorage
from django.conf import settings
import os

class OverwriteStorage(FileSystemStorage):
    def get_available_name(self, name):
        Returns a filename that's free on the target storage system, and
        available for new content to be written to.

        Found at

        This file storage solves overwrite on upload problem. Another
        proposed solution was to override the save method on the model
        like so (from

        def save(self, *args, **kwargs):
                this = MyModelName.objects.get(
                if this.MyImageFieldName != self.MyImageFieldName:
            except: pass
            super(MyModelName, self).save(*args, **kwargs)
        # If the filename already exists, remove it as if it was a true file system
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name

In model this should be set as:

from import OverwriteStorage

class Thing(models.Model):
    image = models.ImageField(
        max_length=SOME_CONST, storage=OverwriteStorage(), upload_to=image_path


Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓