I have this form:
<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>
This is my view, it receives a file from that 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.")
I do not want the page to reload again after submitting the file so i want to use ajax and jquery for this. Call the view through the url and execute the code. This is the 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.
To do this i am using this code:
<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
}
});
});
So, running this i see that the view is called correctly with a POST method, BUT there is no file getting to the view, the request is empty:
Obviously i am doing something or many things wrong but i can not see where.
Thanks in advance for any help