Django FileField not validating with a SimpleUploadedFile Object

I am uploading a file via ajax, and then creating a SimpleUploadFile object and passing it to replace request.FILES -- this does not pass form.is_valid(). I've logged the SimpleUploadedFile dictionary and request.FILES replacement below; as you can see, the SimpleUploadedFile object is able to be created:

SimpleUploadedFile [This does not work.]:
{'book_pics': <SimpleUploadedFile: movies.jpg (text/plain)>} # Yielded by printing uploaded_file

When I don't use ajax and simply use the form to submit the file [I did this out of curiousity], here is what uploaded_file looks like:

request.FILE generated InMemoryUploadedFile [This works.]:
<MultiValueDict: {u'book_pics': [<InMemoryUploadedFile: movies.jpg (image/jpeg)>]}>

Any idea of how I could get the SimpleUploadedFile to validate?

def add_book(request):
    if request.method == 'POST':
        # Grabbing the file uploaded via ajax earlier.
        fh = File(file(settings.MEDIA_ROOT + request.POST['book_pics']))
        uploaded_file = {'book_pics':SimpleUploadedFile(fh.name, fh.read())}
        form = BookForm(data=request.POST, files=uploaded_file)
        if form.is_valid():
            print >> sys.stderr, "Form is valid."
            form.save()
            return render(request, 'generic_message.html', {'message': 'Succesfully added book.'})
        else:
           ...
    else:
        ...

According to these docs, SimpleUploadedFile should work: https://docs.djangoproject.com/en/dev/ref/forms/api/

EDIT:

When I print f.clean(my_file) I get the following error, context below. This happens with and without setting filetype in my_file:

fh = File(file(settings.MEDIA_ROOT + request.POST['book_pics']))
my_file = UploadedFile(fh.name, fh.read(), 'image/jpeg')
f = forms.FileField()
print >> sys.stderr, f.clean(my_file)
# f.clean(my_file) Returns an error: 

DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 18: invalid 
start byte. You passed in '<UploadedFile: 
Xx06x18x92HIxdexf0x00xddx7fnx8exf9x8fxe5x00x92IGaxaaxcexfe_xa4x04xe
3xcax1a,x97x99xd0xdax02xe3exa8xbb=x99xe0x00x0bxfd?
Qx00x02x80x00*xe6xf7xb0xd6xfb@x06xd2x1f7xfdxafx00x04Iw}x8bx08xbcxBxc
bjx1exa3x7f1xf9xc3xc3xef"rxfbxcc"Txa2x01rxe7Xxb0xa3xc4rxeaxdfx9cx00>
x96Kx0bxeex07xd26<xa0rxb8xf2?xa4x94xf96xe43x1fxc5xfax1fxd8@ 
txe9xeax7f8x00p?Sxf9xc0x01xc6xaax1bx06axca-
x1fxbax88xa6xedn,|'xa2xd8txb0x862xb0xfax17x16<xf7x80xc1xcexc3xccx
fex91Xpx02xc5x92x96xb3xa9x8boxac8x0eQxa1xf3x80x07(xf8GRxf1xxf0x80($xa
8x02K76xda4x03hx07x9fxedx00x07x1fx12Fxc7xfbCxc3x90x16txcaxeeu;xf4x8a
x92x9f#xa4x12Arxf7x80AxcaIdxdfRxc7xaexb0xf0x01i%xc5xf7x8ax80PItxb9xb
9 xfd`x01xc2Ixe6}x81x1bx7f*7x8ax1c'O|x84xc1xc...

From one of my tests:

name = 'filename'
f = file(self.TEST_ROOT + name)
file_data = {'file':SimpleUploadedFile(f.name,f.read())}
data = {}
form = self.TestForm(data,file_data)
self.assertTrue(form.is_valid())

This test is passing. My code is almost identical to yours, except i'm not passing a File but a file to the form. And i do not name the arguments passed. Both differences don't make a difference, i have tried that. Your problem is that in

file(settings.MEDIA_ROOT + request.POST['book_pics'])

request.POST['book_pics'] does contain the filename, but your file is not in MEDIA_ROOT. It is in the location where django puts temporary uploaded files, or, if it is a small file, it is in memory. Either way the path you create with your code does not point to the file.

If you try to send the file via ajax, and not with a form, you can do that with a solution like this one: http://kuhlit.blogspot.de/2011/04/ajax-file-uploads-and-csrf-in-django-13.html Have a look at the django code somewhere in the middle of that page.

Quite complex, but it works.

链接地址: http://www.djcxy.com/p/56554.html

上一篇: JQuery将文件发送给Django

下一篇: Django FileField不用SimpleUploadedFile对象进行验证