Django Jquery / Ajax文件在POST中没有上传文件

时间:2018-03-14 22:03:42

标签: javascript python jquery ajax django

我正在努力将csv上传到django应用程序。我遇到的问题是我无法通过该文件并能够以我的视图访问该文件。没有错误

form.py:

class FileUploadForm(forms.Form):
   csv_file = forms.FileField()

HTML:

<form action="{% url 'ajax-view' %}" method="post" 
enctype="multipart/form-data" id="fileForm">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload" />
</form>

js file:

// i've tried to add this as well passing file and data to the ajax
  var file;
  $('#id_csv_file').on('change', function(){
  file = event.target.files;
});

$('#fileForm').on('submit', function(e){
  e.preventDefault();
  var data = new FormData($('#fileForm').get(0));
  data.append('file', $('#id_csv_file')[0].files);

  var csrftoken = getCookie('csrftoken');

$.ajax({
      type: "POST",
      headers: {'X-CSRFToken': csrftoken},
      url: '/ajax/view',
      data: {'file': data},
      processData: false,
      contentType: false,
      dataType: "json",
      success:function(data) {

        // display the new data
        console.log(data)

      }
  });

});

我的观点是:

def view(request):
    form = FileUploadForm()
    return render(request, 'template.html', { 'form':form })

def ajax_view(request):
    if request.method == "POST":
      print request.POST
      print request.FILES

以上打印显示: <QueryDict: {}> <MultiValueDict: {}>

0 个答案:

没有答案