title: Save related Images Django REST Framework
body: <p>I have this basic model layout:</p>
  
  <pre><code>class Listing(models.Model):
      name = models.TextField()
  
  class ListingImage(models.Model):
      listing = models.ForeignKey(Listing, related_name='images', on_delete=models.CASCADE)
      image = models.ImageField(upload_to=listing_image_path)
  </code></pre>
  
  <p>Im trying to write a serializer which lets me add an rest api endpoint for creating Listings including images.</p>
  
  <p>My idea would be this:</p>
  
  <pre><code>class ListingImageSerializer(serializers.ModelSerializer):
      class Meta:
          model = ListingImage
          fields = ('image',)
  
  class ListingSerializer(serializers.ModelSerializer):
      images = ListingImageSerializer(many=True)
  
  class Meta:
      model = Listing
      fields = ('name', 'images')
  
  def create(self, validated_data):
      images_data = validated_data.pop('images')
      listing = Listing.objects.create(**validated_data)
      for image_data in images_data:
          ListingImage.objects.create(listing=listing, **image_data)
  
      return listing
  </code></pre>
  
  <p>My Problems are:</p>
  
  <ol>
  <li><p>I'm not sure how and if I can send a list of images in a nested dictionary using a multipart POST request.</p></li>
  <li><p>If I just post an images list and try to convert it from a list to a list of dictionaries before calling the serializer, I get weird OS errors when parsing the actual image.</p>
  
  <pre><code>for key, item in request.data.items():
      if key.startswith('images'):
          # images.append({'image': item})
          request.data[key] = {'image': item}
  </code></pre></li>
  </ol>
  
  <p>My request code looks like this:</p>
  
  <pre><code>import requests
  from requests_toolbelt.multipart.encoder import MultipartEncoder
  
  api_token = 'xxxx'
  
  images_data = MultipartEncoder(
      fields={
          'name': 'test',
          'images[0]': (open('lilo.png', 'rb'), 'image/png'),
          'images[1]': (open('panda.jpg', 'rb'), 'image/jpeg')
      }
  )
  
  
  response = requests.post('http://127.0.0.1:8000/api/listings/', data=images_data,
                           headers={
                               'Content-Type': images_data.content_type,
                               'Authorization': 'Token' + ' ' + api_token
                           })
  </code></pre>
  
  <p>I did find a very hacky solution which I will post in the answers but its not really robust and there needs to be a better way to do this.</p>