Реализовал это так:
index.js:
$(document).ready(function () {
$('#file').change(function () {
//var formdata = new FormData($('#loadImageForm')[0]);
var fileInput = document.getElementById('file');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('photo', file);
if (formData) {
$.ajax({
url: "uploadImage",
type: "POST",
data: formData,
headers: { "X-CSRFToken": getCookie("csrftoken") },
processData: false,
contentType: false,
success: function () {
console.log('success');
},
error: function (error) {
console.log(error);
}
});
}
});
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
});
views.py:
def uploadImage(request):
if request.method == 'POST':
form = forms.FileUploadForm(data=request.POST, files=request.FILES)
if form.is_valid():
print('Done')
else:
print(form.errors)
return HttpResponse('test')
Благодаря
alternativshik и
Сергей Горностаев