Validating form file fields is hard
|Reported by:||Ole Laursen||Owned by:||nobody|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I have an application where I need to validate a file uploaded through a form. I'd like to do this with the clean_xxx() method for the field. However, I need the file to be present in the file system because the validation is using external libraries and applications.
I don't think that's an unreasonable requirement, but it is not straightforward with the current API. After some digging, I thought I could use the storage classes, something like
f = self.cleaned_data['myfile'] storage = FileSystemStorage(location="/tmp") path = storage.save(tempfile.mktemp(dir="/tmp"), f) try: if not validate_file(path): raise forms.ValidationError(...) finally: storage.delete(path)
But this doesn't work with the temporary file backend because it opens and closes the file, and as far as I can tell, there's no straight-forward way of reopening it again. So currently, I'm doing something like this:
f = self.cleaned_data['myfile'] if hasattr(f, 'temporary_file_path'): path = f.temporary_file_path() cleanup = False else: import tempfile path = tempfile.mktemp(dir="/tmp") from django.core.files.storage import FileSystemStorage storage = FileSystemStorage(location="/tmp") path = storage.save(path, f) cleanup = True try: if not validate_file(path): raise forms.ValidationError(...) finally: if cleanup: storage.delete(path)
It occurs to me that the API ought to have a more elegant way of doing this?
Change History (8)
comment:1 Changed 6 years ago by
|Component:||Uncategorized → File uploads/storage|
|Triage Stage:||Unreviewed → Accepted|