Django / Python:无法将文件发送到视图

时间:2015-09-25 18:38:30

标签: jquery python ajax django

我有这样的表格:

INSERT INTO new_db.posts (title, content) VALUES SELECT db1.title, db1.content FROM old_db.posts db1

这是我的看法,它从该表单接收文件:

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

我不希望在提交文件后再次重新加载页面,所以我想为此使用ajax和jquery。通过url调用视图并执行代码。这是网址:

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

为此,我使用此代码:

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.

所以,运行这个我看到用POST方法正确调用了视图,但是没有文件到达视图,请求是空的:

enter image description here

显然我正在做一些事情或许多事情错了,但我看不出去哪里。

提前感谢您提供任何帮助

1 个答案:

答案 0 :(得分:0)

好的,这就是我设法将文件发送到我的视图的方式:

$("#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
                }
        });
   });

现在到了那里,代码正在运行。

我无法看到从视图中返回的数据,但我将继续处理它。感谢您的评论