Django file upload – How to check if filename already exists in disk

Use this solution to raise an error when the uploaded file has the same name as a previously stored file in system.

In the following code, the FileField is named my_file. The clean_my_file method ensures that the user will be informed if the filename already exists in the destination directory and will prevent the user from saving the file.

import os.path
from django.conf import settings

def clean_my_file(self):
    my_file = self.cleaned_data.get("my_file", False)
    destination = settings.MEDIA_ROOT + 'some_folder/'
    if os.path.isfile(destination +
        raise forms.ValidationError('A file with the name "''" already exists. Please, rename your file and try again.')
        return my_file