2015-09-25 71 views
0

我有這樣的形式:Django的/ Python的:不能夠將文件發送到視圖

<form id="formi" method="POST" enctype="multipart/form-data"> 
{% csrf_token %} 
    <div> 
     <input id="some_file_input" type="file" name="some_file""> 
    </div> 
    <button type="submit" id="upload-file-btn">Submit</button> 
</form> 

這是我的看法,它收到來自該格式的文件:

def d_s_w(request): 

    if request.is_ajax() and request.method == "POST": 

     if len(request.FILES) != 0: 

      data = request.FILES['some_file'] 

      ... 

      context = {'dates': dates, 'users': users} 

      data = json.dumps(context) 

      return HttpResponse(data, content_type="application/json") 
     else: 
      raise Http404("No File uploaded") 
    else: 
     raise Http404("No POST data was given.") 

我做不希望頁面在提交文件後重新加載,所以我想爲此使用ajax和jquery。通過url調用視圖並執行代碼。這是網址:

url(r'^$', views.index, name='index'), ------->this is the page with the form, i do not want this page to reload 

url(r'^work/$', views.d_s_w, name='d_s_w'),--->page that points to the view that takes the file and does some work with that file. 

要做到這一點,我使用此代碼:

<script> 
    $("#formi").submit(function(event){ 
     event.preventDefault(); 
     $.ajax({ 
      type:"POST", 
      url:"{% url 'd_s_w' %}", 
      data: { 
        file: $('form').serialize(), 
        }, 
      success: function(data){ 
        console.log("success") 
       }, 

      error : function(xhr) { 
        console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console 
       } 
     }); 
    }); 

所以,運行這個我看到的視圖與POST方法正確調用,但沒有文件得到的觀點,要求是空的:

enter image description here

顯然我做了一些事情或很多事情錯誤,但我看不到在哪裏。

預先感謝任何幫助

+0

processData:false, contentType:false在ajax也許? –

+0

@PauloPessoa沒有運氣,謝謝你的提示,雖然 – NachoMiguel

+1

http://stackoverflow.com/questions/20822823/django-jquery-ajax-file-upload看看這個,也許幫助你 –

回答

0

OK,這就是我設法將文件發送給我的觀點:

$("#formi").submit(function(event){ 
    event.preventDefault(); 
    var data = new FormData($('form').get(0)); 

     $.ajax({ 
      type:"POST", 
      url:"{% url 'd_s_w' %}", 
      data: data, 
      processData: false, 
      contentType: false, 
      csrfmiddlewaretoken: '{{ csrf_token }}', 

      success: function(data){ 
        console.log("success") 
       }, 

      error : function(xhr) { 
        console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console 
       } 
     }); 
    }); 

現在越來越有和運行代碼。

我無法看到從視圖中返回的數據,但我會處理它。感謝您的意見

相關問題