@any_field.register(models.FilePathField)<EOL>def any_filepath_field(field, **kwargs):
def get_some_file(path):<EOL><INDENT>subdirs, files = [], []<EOL>for entry in os.listdir(path):<EOL><INDENT>entry_path = os.path.join(path, entry)<EOL>if os.path.isdir(entry_path):<EOL><INDENT>subdirs.append(entry_path)<EOL><DEDENT>else:<EOL><INDENT>if not field.match or re.match(field.match,entry):<EOL><INDENT>files.append(entry_path)<EOL><DEDENT><DEDENT><DEDENT>if files:<EOL><INDENT>return random.choice(files)<EOL><DEDENT>if field.recursive:<EOL><INDENT>for subdir in subdirs:<EOL><INDENT>result = get_some_file(subdir)<EOL>if result:<EOL><INDENT>return result<EOL><DEDENT><DEDENT><DEDENT><DEDENT>result = get_some_file(field.path)<EOL>if result is None and not field.null:<EOL><INDENT>raise TypeError("<STR_LIT>" % field.path)<EOL><DEDENT>return result<EOL>
Lookup for nearest existing file