How to Override/Replace Uploaded file with same name in Django

How to Override/Replace Uploaded file with same name in Django


In this Django tutorial, I will show you how you can override the existing uploaded file with the new one if the new one has the same name as the existing one.

For this tutorial, I'm assuming that you have done with the file uploading and you are successfully uploading the files to your media.

So let's start. To override the existing files you need to define your own file system as original.
First, make a new file storage.py in your app and copy-paste the code given below and save the file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django.core.files.storage import FileSystemStorage
from django.conf import settings
import os


class OverwriteStorage(FileSystemStorage):

    def get_available_name(self, name, max_length=None):
        # 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

Now, in your models.py import OverwriteStorage and edit your model's ImageField and add a new argument storage=OverwriteStorage() as shown on line 5.

I'm working with ImageField but you can use others as well.

1
2
3
4
5
from .storage import OverwriteStorage

class Image(models.Model):
    image = models.ImageField(
        upload_to='uploaded/images', storage=OverwriteStorage())

Note: Before running your server make sure you have run the migration command.

No comments