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方法正確調用,但沒有文件得到的觀點,要求是空的:
顯然我做了一些事情或很多事情錯誤,但我看不到在哪裏。
預先感謝任何幫助
processData:false, contentType:false在ajax也許? –
@PauloPessoa沒有運氣,謝謝你的提示,雖然 – NachoMiguel
http://stackoverflow.com/questions/20822823/django-jquery-ajax-file-upload看看這個,也許幫助你 –