# extra py - The Custom FileFiled

from django.db.models import FileField
from django.forms import forms

class CustomCheckFileField(FileField):
    def __init__(self, custom_check=None, error_message=None, **kwargs):

        self.error_message=error_message

        if callable(custom_check):
            self.custom_check = custom_check

        super(CustomCheckFileField, self).__init__(**kwargs)

    def clean(self, *args, **kwargs):
        data = super(CustomCheckFileField, self).clean(*args, **kwargs)

        file = data.file

        #args[1] is the model instance
        if not self.custom_check(args[1], self.generate_filename(args[1], file.name)):
            raise forms.ValidationError(self.error_message)
        return data

    def custom_check(self, filename):
        return True



#custom FileSystemStorage which return same name for existing file (also deletes existing files on save
#some_other.py
from django.core.files.storage import FileSystemStorage

class OverwriteStorage(FileSystemStorage):

    def _save(self, name, content):
        if self.exists(name):
            self.delete(name)
        return super(OverwriteStorage, self)._save(name, content)

    def get_available_name(self, name):
        return name


#usage
#models.py

def _custom_media_file_unique(instance, filename):
    existing = CustomMedia.objects.filter(file=filename)
    if existing and existing.count() > 1:
        return False
    else:
        if existing:
            return existing[0].id == instance.id
    return True

class CustomMedia(models.Model):
    file = CustomCheckFileField(upload_to=_get_media_upload_to, custom_check=_custom_media_file_unique,error_message="File Already Exists",storage=OverwriteStorage())