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 the 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 + my_file.name): raise forms.ValidationError('A file with the name "'+my_file.name+'" already exists. Please, rename your file and try again.') else: return my_file