title: passing data from javascript to django view when uploading a file
body: <p>I created a <code>no javascript</code> code which uses an <code>html form</code> and <code>django view</code> to upload a file .It uses an <code>html5 input</code> element for selecting the file.On clicking the <code>submit</code> button,the file gets uploaded without any problem.The django view can get the file from <code>request.FILES</code></p>
  
  <pre><code>def upload_file(request,template_name):
      to_return = {}
      store_message="failure"
      if request.method == 'POST':
          if request.FILES.has_key('fselect'):
              file = request.FILES['fselect']
              with open('/uploadpath/%s' % file.name, 'wb+') as dest:
                  for chunk in file.chunks():
                      dest.write(chunk)
              store_message="success"
      to_return['store_message']= store_message
      if store_message == "failure":
          return redirect('home')
      reqctx = RequestContext(request,to_return)
      return return render_to_response(template_name,reqctx)
  </code></pre>
  
  <p>the html form is</p>
  
  <pre><code>    &lt;form enctype="multipart/form-data" method="post" action="{% url uploaded %}"&gt; {% csrf_token %}
      &lt;input type="file" name="fselect" id="fselect"&gt;    &lt;/input&gt;
      &lt;input type="submit" id="uploadbtn" value="upload"&gt;    
      &lt;/form&gt;
  </code></pre>
  
  <p>Now I want to use some <code>javascript</code> to call the <code>django</code> view .
  I have coded ajax version of upload view</p>
  
  <pre><code>def ajax_upload_file(request):
      to_return = {}
      store_message="failure"
      if request.method == 'POST':
          if request.FILES.has_key('fselect'):
              file = request.FILES['fselect']
              with open('/uploadpath/%s' % file.name, 'wb+') as dest:
                  for chunk in file.chunks():
                      dest.write(chunk)
              store_message="success"
       to_return['store_message']= store_message
       serialized = simplejson.dumps(to_return)
       if store_message == "failure":
          return HttpResponseServerError(serialized, mimetype="application/json")
       else:
          return HttpResponse(serialized, mimetype="application/json")
  </code></pre>
  
  <p>I am confused about how the <code>file</code> object can be passed from <code>javascript</code> code to django view.</p>
  
  <p>javascript code</p>
  
  <pre><code>$(document).ready(function(){
    $('#fselect').change(function(){uploadFile()});
  
  }
  function uploadSubTitleFile(){
      //check if it is a subtitle file?
      var file=document.getElementById('fselect').files[0];
      var data = {  };//how to pass the data
      var args = { type:"POST", url:"ajax_upload/", data:data, complete:done };    
      return;
  }
  </code></pre>