1

我正在尝试ajax file upload in django。我编码javascript ,django view如下。文件上传成功。然后我为视图编写了一个测试方法。执行测试时,文件成功上传到目标文件夹。但是,我得到了一些奇怪的错误.

在应用程序中执行 ajax 上传时不会发生此特定错误。它仅在执行测试时发生。

$(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'){
          }
       }
    }
}
...

django 视图

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")

来自 urls.py 文件的片段

网址.py

...
url(r'^upload/$', 'myapp.views.ajax_upload',name='ajax_upload'),
...

最后,这是测试方法

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'))

如您所见,我在视图代码中放置了一些打印语句,它们显示request.FILES['file']具有正确的值(即mydoc.doc)并且上传成功(我可以看到文件复制到 dest 文件夹)。

现在这里是显示错误消息的控制台输出

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)

我无法弄清楚为什么会发生这种情况..有人可以帮我解决这个问题吗?

4

1 回答 1

3
resp = self.client.post(self.client.post(...))

别担心,每个人都会遇到:)

于 2012-06-23T18:36:53.480 回答