Open uploaded file while still in memory; In the Form Clean method?

121 views
Skip to first unread message

Ty

unread,
Mar 11, 2009, 12:57:21 PM3/11/09
to Django users
I need to validate an uploaded XML file in my Form clean method, but
I'm unable to open the file for validation. It seams, in the clean
method, the file hasn't yet been moved from memory (or the temporary
directory) to the destination directory.

For example the following code would fail because the file hasn't been
moved to that destination yet. It's still in memory (or the temporary
directory):

# This is in my Form clean method:
xml_file = cleaned_data.get('xml_file')
xml_file_absolute = '%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2':
xml_file}
xml_size = str(os.path.getsize(xml_file_absolute))

When I look at the "cleaned_data" variable it shows this:
{'xml_file': <InMemoryUploadedFile: texting.nzb (application/octet-
stream)>}

cleaned_data.get('xml_file') only returns "texting.nzb" as a string.

Is there another way to access the the file in memory (or the
temporary directory)?

Rajesh D

unread,
Mar 11, 2009, 4:23:29 PM3/11/09
to Django users
What you get in cleaned_data can double as an open file handle from
which you can directly start reading:

xml_file = cleaned_data.get('xml_file')
value = xml_file.read()
# Do whatever validation you need on value
xml_file.seek(0) # Reset the file to the beginning as you found it.

Obviously, for larger files, you should read and process the data in
smaller
chunks instead of the above xml_file.read().

There's more info here: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/#handling-uploaded-files

-Rajesh D

Reply all
Reply to author
Forward
0 new messages