djangodjango-modelsdjango-uploads

Django add random character in filename


I want to upload an image and overwrite it if the file exists without changing the filename. I can already overwrite the file but django always add random char on the end of the filename. How can I overwrite it with the same filename? Here is my code.

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

Solution

  • 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