Django Rest Framework upload multiply images at once with serializer
<p>I had some research on web for this problem on DRF. When one image is in post DRF works great. But when 3 or 5 images are in one post there is problem that Django save only first image from POST query and others are not saved in database.
The question is how to properly handle multiply images upload in one post.</p>

<h1>Description</h1>

<blockquote>
  <p>Django version</p>
</blockquote>

<ul>
<li>1.10</li>
</ul>

<blockquote>
  <p>Rest framework version</p>
</blockquote>

<ul>
<li>3.4.6</li>
</ul>

<blockquote>
  <p>Python version</p>
</blockquote>

<ul>
<li>3.5</li>
</ul>

<p>Here is my code what I was trying to do:</p>

<h1>models</h1>

<pre><code>class UserModel(AbstractEmailUser):
    first_name = models.CharField(max_length=30, db_index=True)
    last_name = models.CharField(max_length=50, db_index=True)
    details = JSONField(null=True, blank=True, db_index=True)
    avatar = models.ImageField(blank=True, null=True, upload_to='avatar')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.email)

class UserImages(models.Model):
    image = models.ImageField(upload_to='images', db_index=True)
    user = models.ForeignKey('UserModel',related_name='user')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.user)
</code></pre>

<p>Here in models I have related field from User to UserImages. For purpose on POST query from postman I manual add ID from user to handle FK.</p>

<h1>serializer</h1>

<pre><code>class SerializerUserImages(serializers.ModelSerializer):

    class Meta:
        model = UserImages

    def create(self, validated_data):
        imgs = UserImages.objects.create(**validated_data)
        return imgs
</code></pre>

<p>Maybe here I must do some for loop to accomplish save method for multiply images.</p>

<h1>views</h1>

<pre><code>class UploadImages(APIView):
    authentication_classes = (JSONWebTokenAuthentication,)

    @parser_classes((FormParser, MultiPartParser, FileUploadParser))
    def post(self, request, format=None):

        serializer = SerializerUserImages(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(data={"msg": serializer.data}, status=status.HTTP_200_OK)
        else:
            return Response(data={"msg": serializer.errors}, status=status.HTTP_406_NOT_ACCEPTABLE)
</code></pre>

<p>All parsers are included for handling this post query.</p>

<p>This is output from <strong>request.data</strong> = <code>&lt;QueryDict: {'image': [&lt;InMemoryUploadedFile: top_20_cro.png (image/png)&gt;, &lt;InMemoryUploadedFile: images.jpg (image/jpeg)&gt;], 'user': ['2', '2']}&gt;</code></p>

<p>This is copy of request POST from POSTMAN:</p>

<pre><code>POST /api/images/ HTTP/1.1
Host: 127.0.0.1:8000
Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcmlnX2lhdCI6MTQ3MjIwMTcwMSwiZXhwIjoxNDcyMjMxNzAxLCJ1c2VyX2lkIjoyLCJlbWFpbCI6Im1hcmluLmJyZWthbG9AZ21haWwuY29tIiwidXNlcm5hbWUiOiJtYXJpbi5icmVrYWxvQGdtYWlsLmNvbSJ9.Fi3kmXJ44E_qhHHioniQ-cqri-u2ELU-XmpE_1oJ4Fk
Cache-Control: no-cache
Postman-Token: 1e53ac06-ed37-ff6e-2dc5-117976b86a5e
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="image"; filename=""
Content-Type: 


------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="user"

2
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="filename"

image
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="user"

2
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="filename"

image
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="image"; filename=""
Content-Type: 


------WebKitFormBoundary7MA4YWxkTrZu0gW--
</code></pre>

<p>How can this be handled without some great magic, is there some easy logic that I missed up.</p>

<p>Try setting filenames for your images, I mean replace <code>filename=""</code> with something like <code>filename="image-1"</code>, <code>filename="image-2"</code>, etc. Files should have different filenames or they override each other.</p>

python django image rest file-upload