so i am writing a django form to process file uploads. i have an html (template) form:
it seems like it should be a straightforward matter to access the form variables for the file. but it’s actually quite complex. the response object available to all django functions has a FILE object available to it. so in the process function:
def process(request): # 'request' is a 'WSGIRequest object'. f is a queryDict object-- like a # dictionary object, but keys can have multiple values. f = request.FILES # f.lists() returns a LIST of all file fields in the form fileFields = f.lists() # length of this list should be equal to the number of file upload fields # in the form (in this case, 1) output += str(len(fileFields)) + '' # each element of the fileFields array is a tuple. fileTuple = fileFields[0] # and each element of the tuple is a unicode string representing the 'name' value # specified in the form's file upload field (in this case, 'somename'). formFieldName = fileTuple[0] fileObject = f.__getitem__(formFieldName)
the fileObject is described in this section of the django documentation on request and response objects. it has name and size attributes, and a read() method. so the write the contents of the file to stdout:
size = fileObject.size
output += ' here\'s the file contents: ' + fileObject.read(size)
this should confirm that you are indeed properly getting your file. subsequently you probably want to do something more useful, like save it to disk.
but man, it sure seems bloody long winded to me. is there a better way to do this that i’m missing?
