1

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?

2 Answers2

3

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • If I change both contentType and form instantiation the code hangs on line myform = forms.Form(request.POST, request.FILES). If I dont change content type the form coming is empty – priyam bakliwal Jan 05 '18 at 06:29
  • What do you mean, it hangs? Do you get any kind of error? – Daniel Roseman Jan 05 '18 at 07:31
  • INFO:usermanagement.user: exit login view and execution time 0.0342240333557 (2018-01-05 08:25:34; user.py:71) INFO:usermanagement.user: Inside imageVerify (2018-01-05 08:25:41; user.py:346) Then program hangs. Does not print anything. – priyam bakliwal Jan 05 '18 at 08:26
  • Thanks. This saved me from a stupid bug. Also, I recommend `contentType: false`. – Chris Conlan Nov 24 '18 at 16:21
1

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']