How exactly do I upload a file using an ajax call ? My form in template
<form action="images/" enctype="multipart/form-data" method="POST" class="upload">
<table>
{{ form.as_table }}
<td><input type = "button" onclick="" value="Upload" id = "test"/</td>
</table>
</form>
My jQuery function :
$(document).ready(function(){
$("#test").click(function(){
var string = $("form.upload").serialize();
alert(string);
$.ajax({
url :'/test/',
type:'post',
data: {datas:string},
dataType: "json",
success: function(response) {
alert(response);
}
});
});
});
My view :
@csrf_exempt
def test(request):
if request.is_ajax():
form = ImageUploadForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("Saved !!!!")
Here I have the view for the file upload but the file does not appear in the form variable in the django view . What should I do to get the file in the view ? The form has a filefield for uploading . It is a model form.