ImageField overwrite image file with same name

The default behavior of the Django ImageField when you upload a new image has the same name with an existing image Django will add suffix to that new one:

existingname_<somesuffix>.JPG

But if the image names are identical and represent each object in the database (named after the object's pk), you don't want to have that suffix added. You just want to remove the existing one with the new photo. If that the case, you can define your storage class and assign to the ImageField in models.py like the following example:

1. Create a file name storage.py and put it in the same place with settings.py:

from django.core.files.storage 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 http://djangosnippets.org/snippets/976/

        This file storage solves overwrite on upload problem. Another
        proposed solution was to override the save method on the model
        like so (from https://code.djangoproject.com/ticket/11663):

        def save(self, *args, **kwargs):
            try:
                this = MyModelName.objects.get(id=self.id)
                if this.MyImageFieldName != self.MyImageFieldName:
                    this.MyImageFieldName.delete()
            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

2. In your models.py:

from myproject.storage import OverwriteStorage

# Create your models here.
class MyModel(models.Model):
    ...
    photo = models.ImageField(storage=OverwriteStorage(), upload_to='photos')



Reference: http://stackoverflow.com/questions/9522759/imagefield-overwrite-image-file-with-same-name