How to prevent Django from changing the file name when a file with the same name already exists?

In my case, I allow the user to upload an avatar image and use user_id as the file name, simply. So it will be 1.jpg, 2.jpg, etc.

However, I found that if I upload a new avatar for some account that already has one, say, user # 10 uploaded, the new file will be called "10_1.jpg". This is normal, but I do not need it, and I hope that the new file can overwrite the old one - in any case, it will also save disk space.

I searched Google and searched, but could not find clues. I was hoping there would be an option for ImageField or FileField, but it does not exist.

Thanks for the help!

+6
source share
2 answers

You must define your own storage, inherit it from FileSystemStorage and override the get_available_name function. Use this store for your image. Something like that:

class OverwriteStorage(FileSystemStorage): def get_available_name(self, name): if self.exists(name): os.remove(os.path.join(SOME_PATH, name)) return name fs = OverwriteStorage(location=SOME_PATH) class YourModel(models.Model): image_file = models.ImageField(storage=fs) 
+11
source

Michael Gendin's solution above works fine for Django 2.1 (Hello from 2018!). You must add the max_length attribute to the get_available_name method:

 def get_available_name(self, name, max_length=None): 
0
source

Source: https://habr.com/ru/post/908056/


All Articles