Home > Enterprise >  Multiple Image upload in django rest framework
Multiple Image upload in django rest framework

Time:12-05

How to upload multiple images in DRF. I'm getting all the list of images while looping through it, but it only saves the last one. I want to save all the image and show it in response. Do I have to create separate serializer for Multiple Image serialization?

#models

class ReviewRatings(models.Model):
    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    product = models.ForeignKey(Products, on_delete=models.CASCADE)
    rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)])
    created_at = models.DateField(auto_now_add=True)
    review = models.CharField(max_length=500, null=True)
    updated_at = models.DateField(auto_now=True)


    def __str__(self):
        return self.product.product_name
class ReviewImages(models.Model):
    review = models.ForeignKey(ReviewRatings, on_delete=models.CASCADE, related_name='review_images', null=True, blank=True)
    images = models.ImageField(upload_to='reviews/review-images', null=True, blank=True)

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

#Serilaizer

class ReviewImagesSerializer(ModelSerializer):
   
    class Meta:
        model = ReviewImages
        fields = ["images"]
class ReviewSerializer(ModelSerializer):
    user = SerializerMethodField()
    review_images = ReviewImagesSerializer(many=True)

    class Meta:
        model = ReviewRatings
        fields = [
            "user",
            "rating",
            "review",
            "created_at",
            "updated_at",
            "review_images",
        ]

    def get_user(self, obj):
        return f"{obj.user.first_name} {obj.user.last_name}"

#Views

class SubmitReview(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, product_slug):
        data = request.data
        if data["rating"] == "" and data["review"] == "":
        review = ReviewRatings.objects.create(
            user=request.user,
            product=product,
            rating=data["rating"],
            review=data["review"],
            
        )
        review_images =request.FILES.getlist('review_images') 
        rev = ReviewImages()
        for image in review_images:
            rev.review=review
            rev.images = image
            rev.save()
        
        serializer = ReviewSerializer(review, context={'request':request})
        return Response(serializer.data, status=status.HTTP_201_CREATED)

#Postman enter image description here

Response I get on the current implementation

{
    "user": "Jackson Patrick Gomez",
    "rating": 4.8,
    "review": "Pendant -1 review by jackson with image uploadss",
    "created_at": "2022-12-05",
    "updated_at": "2022-12-05",
    "review_images": [
        {
            "images": "http://127.0.0.1:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
        }
    ]
}

The response I want to get is like this

{
    "user": "Jackson Patrick Gomez",
    "rating": 4.8,
    "review": "Pendant -1 review by jackson with image uploadss",
    "created_at": "2022-12-05",
    "updated_at": "2022-12-05",
    "review_images": [
        {
            "images": "http://127.0.0.1:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
        },
        {
            "images": "http://127.0.0.1:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
        },
        {
            "images": "http://127.0.0.1:8000/media/reviews/review-images/pendant3_rAe0hqS.webp"
        }


    ]
}

I want to upload multiple images.

CodePudding user response:

Are you not saving the same object instance over and over?

rev = ReviewImages()
for image in review_images:
    rev.review=review
    rev.images = image
    rev.save()

Create a new instance for every image:

for image in review_images:
    rev = ReviewImages(review=review, image=image)
    rev.save()

CodePudding user response:

I have found out the mistake. I was only creating one instance. Hence only one object was getting created.

#Mistake

rev = ReviewImages()
for image in review_images:
    rev.review=review
    rev.images = image
    rev.save()

#Correct

for image in review_images:
    rev = ReviewImages()
    rev.review=review
    rev.images = image
    rev.save()

or

for image in review_images:
    ReviewImages.objects.create(images=image, review=review)
  • Related