Reputation: 21
I am trying to to upload an image to Django using Ajax.
Ajax code:
function sendImage() {
console.log(blob);
var fd = new FormData();
fd.append('image', blob);
var tet = $.ajax({
url: '/login/photoverify/',
type: 'POST',
data: fd,
async: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response.driverBeacon);
document.getElementById('username').setAttribute('value', response.username);
},
error: function (error) {
console.log(error);
}
}).responseText;
}
Django Code:
def imageVerify(request):
if request.method == 'POST':
log.info('Inside imageVerify')
myform = forms.Form(request.POST, request.FILES)
log.info("Done loading form")
if myform.is_valid():
log.info(myform.cleaned_data)
file = myform.cleaned_data['image']
But myform.cleaned_data
is empty. Can someone please help?
Upvotes: 1
Views: 3321
Reputation: 21
Solved:
def imageVerify(request):
if request.method == 'POST':
log.info('Inside imageVerify')
myform = forms.Form(request.POST, request.FILES)
log.info("got Myform")
file = myform.files['image']
Upvotes: 1
Reputation: 600059
You haven't passed request.FILES
to the form instantiation.
myform = forms.Form(request.POST, request.FILES)
You might also need to set contentType: 'multipart/form-data'
in the $.ajax()
call.
Upvotes: 3