Django JQuery Ajax File Upload

Here is what I changed to get it working.

  1. I used FormData to package up data from form

  2. Notice the parameters of the form in the Django view. I was not specifying “files” before and that’s what caused the ” file field required” error.

Javascript:

function upload(event) {
event.preventDefault();
var data = new FormData($('form').get(0));

$.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    data: data,
    cache: false,
    processData: false,
    contentType: false,
    success: function(data) {
        alert('success');
    }
});
return false;
}

$(function() {
    $('form').submit(upload);
});

Django View:

def upload_view(request):
    if request.method == 'POST':
        form = FileUploadForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            print 'valid form'
        else:
            print 'invalid form'
            print form.errors
    return HttpResponseRedirect('/ingest/')

Leave a Comment