title: Django JQuery Ajax File Upload
body: <p>I've been trying to upload a simple text file for hours now but I still can't seem to get it working.</p>
  
  <p>I keep getting invalid forms saying I'm missing the "file_source".</p>
  
  <p>Why is "file_source" not getting posted?</p>
  
  <p>I've also got it to actually send "file_source" but it still says it is missing. What type of element should be given to a Django FileFiled?</p>
  
  <p>Django Form:</p>
  
  <pre><code>class FileUploadForm(forms.Form):
      file_source = forms.FileField()
  </code></pre>
  
  <p>Django Template (renders form):</p>
  
  <pre><code>&lt;form action="/upload/" method="post" id="file-upload-form" enctype="multipart/form-data"&gt; {% csrf_token %}
      {{ form }}
      &lt;button type="submit" class="btn btn-primary" id='upload-btn'&gt;Upload&lt;/button&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>JQuery/Ajax Upload:</p>
  
  <pre><code>function uploadFile() {
  $.ajax({
      data: $(this).serialize(),
      type: $(this).attr('method'),
      url: $(this).attr('action')
  });
  return false;
  }
  
  $(function() {
       $('#file-upload-form').submit(uploadFile);
  });
  </code></pre>
  
  <p>Django View Which recieves POST:</p>
  
  <pre><code>def upload_view(request):
  if request.is_ajax():
      form = FileUploadForm(request.POST)
      if form.is_valid():
          print 'valid form'
      else:
          print 'invalid form'
          print form.errors
  return HttpResponseRedirect('/ingest/')
  </code></pre>