I am trying out ajax file upload in django.I coded the javascript ,django view as below.The file gets uploaded successfully.Then I wrote a test method for the view.When the test is executed ,the file gets successfully uploaded to the destination folder.But ,I get some strange error.
This particular error does not occur when ajax upload is performed in the application.It occurs only when the test is executed.
$(document).ready(function(){
$(document).on('change', '#fileselect', function(e){
e.preventDefault();
uploadFile(e);
});
function uploadFile(e){
var form = $('#fileform').get(0);
var formData = new FormData(form);
var file = $('#fileselect').get(0).files[0];
var xhr = new XMLHttpRequest();
formData.append('file', file);
xhr.open('POST', 'upload/', true);
xhr.send(formData);
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
var data = $.parseJSON(xhr.responseText);
var uploadResult = data['message']
if (uploadResult=='failure'){
displayErrorMessage('failed to upload');
}else if (uploadResult=='success'){
}
}
}
}
...
The django view
def ajax_upload(request):
retvals = {}
message="failure"
if (request.method == 'POST'):
if request.FILES.has_key('file'):
file = request.FILES['file']
print 'file=',file
with open(settings.uploadfolder+'/'+fname, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
message="success"
retvals['message']= message
serialized = json.dumps(retvals)
print 'serialized=',serialized
if message == "success":
print 'success'
return HttpResponse(serialized, mimetype="application/json")
else:
return HttpResponseServerError(serialized, mimetype="application/json")
snippet from urls.py file
urls.py
...
url(r'^upload/$', 'myapp.views.ajax_upload',name='ajax_upload'),
...
Finally,here is the test method
class UploadTest(TestCase):
def setUp(self):
super(UploadTest,self).setUp()
self.client.login(username='me',password='mypass')
def test_upload(self):
fname = os.path.join(settings.testfolder,'mydoc.doc')
with open(fname) as fp:
resp = self.client.post(self.client.post(reverse('ajax_upload'),{'file':fp}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'))
As you can see,I've put some print statements in the view code ,and they show that the request.FILES['file'] has correct value (ie mydoc.doc) and the upload was successful(I can see the file copied to the dest folder).
Now here is the console output which shows the error messages
file= mydoc.doc
serialized= {"message": "success"}
success
E
======================================================================
ERROR: test_upload (myapp.tests.UploadTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/me/dev/python/django/myapp/tests.py", line 143, in test_upload_file
resp = self.client.post(self.client.post(reverse('ajax_upload'),{'file':fp}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'))
File "/home/me/Django-1.4/django/test/client.py", line 449, in post
response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
File "/home/me/Django-1.4/django/test/client.py", line 252, in post
parsed = urlparse(path)
File "/usr/lib/python2.6/urlparse.py", line 108, in urlparse
tuple = urlsplit(url, scheme, allow_fragments)
File "/usr/lib/python2.6/urlparse.py", line 147, in urlsplit
i = url.find(':')
AttributeError: 'HttpResponse' object has no attribute 'find'
----------------------------------------------------------------------
Ran 1 test in 0.200s
FAILED (errors=1)
I could not make out why this occurs..can someone help me figure this out?