For a site i just build i have created a custom FileField, AudioFileField. In the AudioFileForm i now want to check wether a file is an audiofile or not. For this i use sox, a commandlinetool i call via subprocess. In the forms to_python function i have copied the code from 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')
After thinking about this, i thought it could be helpfull to just force the TemporaryFileUploadHandler to be used for AudioFileField. That would save me from the trouble of writing my own code to create a temporary file. How can i do that?
Just subclass the TemporaryFileUploadhandler Model and rewrite the save method with your custom validation code. And all the associated rituals :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With