Django add random character in filename

53 Views Asked by At

I want to upload image and overwrite if the file exist without changing the filename. It's already can overwrite the file but django always add random char on the end filename. How can i overwrite with the same filename ? Here are my code.

foto_content_url = models.ImageField(null=True, blank=True, upload_to=foto_path)
def foto_path(instance, filename):
    return '/', filename + '.jpg'])
1

There are 1 best solutions below

5
On BEST ANSWER

How can i overwrite with the same filename?

Please don't. There is a good reason to do that: you can not know in advance if other model objects are referring to the (old) file. If you would thus override this with new content, now all the records that referred to the old file, will refer to the new file.

Perhaps for now, that scenario is impossible, or very unlikely, but as the application grows, eventually it is possible that you introduce other models with FileFields or ImageFields that refer to the same file. It is also a security vulnerability: if a person would upload a new document and someone has access to the old document, they now have access to the new document, which is likely not the intended effect.

If you really want to do this, you can check if the file already exists and remove it in that case:

import os
import os.path

from django.conf import settings

# bad idea
def foto_path(instance, filename):
    filename = f'/{filename}.jpg'
    try:
        os.remove(os.path.join(settings.MEDIA_ROOT, filename))
    except FileNotFoundError:
        pass
    return filename