0

How can I submit a form, uploading a file, to a Django app using JQuery so that I can capture the "success" handler?

I am able to upload a file my Django app using a regular form submit, but I am redirected to a new after the POST is complete (naturally).

The Django views.py snippet for generating the page is:

def adminImportView(request):
    """
    """
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_file(request.FILES['file'])
            return HttpResponseRedirect(reverse('lobbyVisitorLog.view.adminView'))
    else:
        form = UploadFileForm()

    return render(request, 'utils/importDatabase.html', {'form': form});

Which, when no form is being submitted, generates a form block:

<form id="dbImportForm" action="/visitorLog/admin/import/" enctype="multipart/form-data" method="post">
  {% csrf_token %}
  <div class="row">
    <div class="span7">
      <span class="btn btn-success fileinput-button">
        <i class="icon-plus"></i>
        <span>Browse...</span>
        {{ form.file }}
      </span>

      <button type="submit" class="btn btn-primary start" id="buttonImport">
        <i class="icon-upload"></i>
        <span>Start Import</span>
      </button>
    </div>
  </div>
</form>

But, I would to avoid loading a new page when the process is complete. If I change the button to a simple link and hock it using JQuery my form validation fails. My latest attempt at the Javascript block is:

$('#buttonImport').click(function()
{
  if ($('#id_file').val() == '')
  {
    alert("empty file, can't submit!");
    return false;
  }

  $.post(
    '/visitorLog/admin/import/',
    $('#dbImportForm').serialize(),
    function(data)
    {
      alert("all done!");
    },
    "json"
  );
})

How can I tweak my JQuery POST call to properly validate the form on the server end?

Nicholas Pappas
  • 10,439
  • 12
  • 54
  • 87

1 Answers1

0

Use jQuery Form Plugin .

It support AJAX file uploads.

Another solution without Form Plugin is here How to send FormData objects with Ajax-requests in jQuery? but have limited support in browsers.

Community
  • 1
  • 1
emcpow2
  • 852
  • 6
  • 19