Benjamin Smith Max
Benjamin Smith Max

Reputation: 2748

django - uploading file using ajax fails

I am trying to upload picture using ajax in django. When I post the usual way without ajax, it gets uploaded as expected. But when I upload using ajax, I get the success function, but my form gets invalid in the view and the data I get is from the else condition in the view:

{"image":["This field is required."]}

js:

$('#settings-dialog #background-settings #image-device #upload').on('click', function() {
    var modify_frm = $('#settings-dialog #background-settings #image-device #upload-form');
    $.ajax({
        type: modify_frm.attr('method'),
        url: modify_frm.attr('action'),
        data: modify_frm.serialize(),
        dataType: 'json',
        success: function(data) {
            $('#settings-dialog #background-settings #image-device #upload').text(data);
        },
        error: function(data) {
            $('#settings-dialog #background-settings #image-device #upload').text(JSON.stringify(data));
        }
    });
});

What am I missing here? Could you please help me solve this.

View with ajax don't work:

@login_required(login_url='/custom123user/login')
def admin_page_snap_add(request, page_id):
    if not request.user.is_admin:
        return render(request, 'admin_login_invalid.html')
    else:
        page = Page.objects.get(id=page_id)
        if request.user == page.user:
            if request.is_ajax() and request.POST:
                form = PageSnapForm(request.POST, request.FILES)
                if form.is_valid():
                    page_snap = form.save(commit=False)
                    page_snap.page = page
                    page_snap.user = page.user
                    page_snap.save()
                    data = 'Uploaded'
                    return HttpResponse(json.dumps(data), content_type='application/json')
                else:
                    data = form.errors
                    return HttpResponse(json.dumps(data), content_type='application/json')
            else:
                raise Http404
        else:
            return render(request, 'wrong_user.html')

Upvotes: 0

Views: 323

Answers (1)

xyres
xyres

Reputation: 21744

Uploading images using AJAX is not as straight forward as a normal upload.

See this question: How to send FormData objects with Ajax-requests in jQuery?

And then there's a plug-in for jQuery called jQuery Form Plugin. It takes care of all the dirty work for you so you don't have to worry about binding files to the form, etc etc. Here it is: http://malsup.com/jquery/form/

Upvotes: 1

Related Questions