[Django]-Django: Open uploaded file while still in memory; In the Form Clean method?

30👍

I’m assuming that you’ve bound your form to the files using:

my_form = MyFormClass(request.POST, request.FILES)

If you have, once the form has been validated, you can access the file content itself using the request.FILES dictionary:

if my_form.is_valid():
    data = request.FILES['myfile'].read()

The request.FILES[‘myfile’] object is an UploadedFile object, so it supports file-like read/write operations.

If you need to access the file contents from within the form’s clean method (or any method of the cleaning machinery), you are doing it right. cleaned_data.get('xml_file') returns an UploadedFile object. The __str__ method of that object just prints out the string, which is why you see only the file name. However, you can get access to the entire contents:

xml_file = myform.cleaned_data.get('xml_file')
print xml_file.read()

This section of the docs has some great examples: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/

Leave a comment