title: Django with IOS: getting multipart data (json + image) via POST
body: <p>I'm new to both Django and IOS. I got stuck in this multipart data passing and need your advice!</p>
  
  <p>Currently, I am working on an image-uploading function. From client side, I want to send the image file together with additional information (e.g. access_token). On the server side, I try to get the json data via request.raw_post_data and image via reuqest.FILES</p>
  
  <p>It turns out that, I could only get either JSON data or Image, not both. What's worse, client side only returns 500 error with no other information...</p>
  
  <p>Here's <strong>client code</strong></p>
  
  <pre><code>NSURL *url = [NSURL URLWithString:urlPath];
  AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
  
  // The parameter to send
  NSDictionary * params = dictionaryToSent;
  
  // the image need to upload
  NSData *imageData = UIImageJPEGRepresentation(image, 1);
  NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"" parameters:params constructingBodyWithBlock: ^(id &lt;AFMultipartFormData&gt;formData) {
      [formData
       appendPartWithFileData:imageData
       name:@"image"
       fileName:@"uniqueFileName"
       mimeType:@"image/jpeg"];
  }];
  
  AFJSONRequestOperation* jsonOperation=[[AFJSONRequestOperation alloc]initWithRequest:request];
  
  [jsonOperation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
  
      NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);
  
  }];
  
  [jsonOperation setCompletionBlockWithSuccess: ^(AFHTTPRequestOperation *operation, id JSON) {
  
     // Handler for request is completed    
  }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      //Handler for request is failured;
  }];
  
  [jsonOperation start];
  </code></pre>
  
  <p>And I tried two methods on the <strong>server side</strong>. one is with form which gave me 500 error</p>
  
  <pre><code>form = UploadFileForm(request.POST, request.FILES)
  </code></pre>
  
  <p>the other is like below (pls ignore the indentation problem)</p>
  
  <pre><code>data=json.loads(request.raw_post_data)
  ck_token = data['access_token']
  if 'image' in request.FILES:
  upload = request.FILES['image']
  filename = upload.name
  user = Basic.objects.get(ck_token = ck_token)
  post = Post(user_id = user.user_id, image = upload, caption = "Hello World")
  post.save()
  ret_json = { 
      'success': True, 
      'post_id': post.id
  }
  else:
  ret_json = { 
      'success': False,
      'error_message': "image not found"
  }
  </code></pre>
  
  <p>with the second method, I could get image uploaded but no access_token found. I'm wondering where the access_token has been stored -.-||| Or is it the problem with client side?</p>
  
  <p>Your help is much appreciated!!!!</p>