我可以只为某个FileField使用TemporaryFileUploadHandler吗?

时间:2011-03-05 21:01:58

标签: django

对于我刚构建的网站,我创建了一个自定义FileField,AudioFileField。在AudioFileForm中,我现在想检查一个文件是否是一个音频文件。为此我使用sox,我通过子进程调用commandlinetool。在表单to_python函数中,我复制了ImageFileField中的代码:

#Either we have a path or we
# have to create a temporary one.
if hasattr(data, 'temporary_file_path'):
    file = data.temporary_file_path()
else:
    if hasattr(data, 'read'):
        file = StringIO(data.read())
    else:
        file = StringIO(data['content'])
    # save file to temporary_file_path? Where is temporary_file_path?
    # can i get temporary_file_path from settings, defaults?

check = subprocess.Popen([sox,'--i','-t','%s'%self.path], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
filetype = check.communicate()[0]
if not filetype:
    raise forms.ValidationError('File is not an audiofile')

在考虑了这个之后,我认为强制将TemporaryFileUploadHandler用于AudioFileField可能会有所帮助。这样可以省去编写自己的代码来创建临时文件的麻烦。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

只是将TemporaryFileUploadhandler模​​型子类化,并使用自定义验证代码重写save方法。以及所有相关的仪式:)