title: Upload file from iPhone to Django
body: <p>Sorry, a beginner's question: I have a very simple function in my Django application with which I can upload a file from a web browser to my server (works perfectly!). Now, instead of the web browser, I would like to use an iPhone. </p>
  
  <p>I got a bit stuck as I don't really know how to provide Django with a valid form, i.e. we need a file name and enctype="multipart/form-data" as far as I understand.</p>
  
  <p>Here is my upload function in Django:</p>
  
  <pre><code>class UploadFileForm(forms.Form):
      file  = forms.FileField()
  
  def handle_uploaded_file(f):
      destination = open('uploads/example.txt', 'wb+')
      for chunk in f.chunks():
          destination.write(chunk)
      destination.close()
  
  def upload_file(request):
      if request.method == 'POST':
          form = UploadFileForm(request.POST, request.FILES)
          if form.is_valid():
              handle_uploaded_file(request.FILES['file'])
              print form
              print request.FILES
              return HttpResponse('Upload Successful')
      else:
          form = UploadFileForm()
      return render_to_response('upload.html', {'form': form})
  </code></pre>
  
  <p>My template looks like this (upload.html):</p>
  
  <pre><code>&lt;form action="" method="post" enctype="multipart/form-data"&gt;
      {{ form.file }}
      {{ form.non_field_errors }}
      &lt;input type="submit" value="Upload" /&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>Now, let's suppose that I want to send a simple txt file from my iPhone app to the sever.
  <strong>I don't really know how to</strong>: </p>
  
  <ol>
  <li>provide the file name</li>
  <li>specify the <code>enctype</code> and</li>
  <li>make sure that it's in a format Django can read</li>
  </ol>
  
  <p>This is how far I got:</p>
  
  <pre><code>NSString *fileContents = [self loadTXTFromDisk:@"example.txt"];
  
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
                                  initWithURL:[NSURL 
                                               URLWithString:@"http://127.0.0.1:8000/uploadfile/"]];
  
  
  [request setHTTPMethod:@"POST"];
  [request setValue:@"text/xml"   forHTTPHeaderField:@"Content-type"];
  [request setValue:[NSString stringWithFormat:@"%d", [fileContents length]] 
                                  forHTTPHeaderField:@"Content-length"];
  [request setHTTPBody:[fileContents dataUsingEncoding:NSUTF8StringEncoding]];
  
  NSURLConnection *theConnection = [[NSURLConnection alloc] 
                                    initWithRequest:request 
                                    delegate:self];
  </code></pre>
  
  <p>However, Django will not except this as the form it expects is not valid. Cf. above:</p>
  
  <pre><code>form = UploadFileForm(request.POST, request.FILES)
  if form.is_valid(): #this will not be true ...
  </code></pre>