Home > Mobile >  django rest upload multiple images
django rest upload multiple images

Time:05-24

I'm working on an e-commerce API with Django rest framework so I want when the user adds a new product he can upload multiple images how can I do that with rest framework? here are my models, views, serializer

my models.py

    class Product(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField(null=True, blank=True)
    owner = models.ForeignKey(User, related_name='Products', on_delete=models.CASCADE,null=True)
    class ProductImages(models.Model):
     product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
     images = models.FileField(upload_to='API/images',max_length=100,null=True)

my serializer

class ProductImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductImages
        fields = '__all__'
class Productserializer(serializers.ModelSerializer) :
    images= ProductImageSerializer(many=True)
    class Meta:
        model = Product
        fields = ('id','title','price','description','whatfor','categories','size','rooms','Location','Lat','Long','owner_id','images')
        extra_kwargs = {"user":{"read_only":True}}
        
    def validate(self, attrs):
        attrs['owner'] = self.context.get("request").user
        return attrs   

my views

class ProductViewSet(ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = Productserializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_class = ProductFilter
    search_fields = ['title', 'description']
    ordering_fields = ['price', 'last_update']
    def get_serializer_context(self):
        return {'request': self.request}

CodePudding user response:

I think to implement multiple upload, you need to set the additional field for uploading in the ProductSerializer.

class Productserializer(serializers.ModelSerializer) :
    images= ProductImageSerializer(many=True, read_only = True)
    uploaded_images = serializers.ListField(
        child = serializers.FileFiled(max_length = 1000000, allow_empty_file = False, use_url = False)
        write_only = True
    )
    
    class Meta:
        model = Product
        fields = ('id', ...,'images', 'uploaded_images', ) # add the field
        extra_kwargs = {"user":{"read_only":True}}
        
    def create(self, validated_data):
        uploaded_data = validated_data.pop('uploaded_images')
        new_product = Product.objects.create(**validated_data)
        for uploaded_item in uploaded_data:
            new_product_image = ProductImages.objects.create(product = new_product, images = uploaded_item)
        return new_product

And in the frontend, you need to change the key images into uploaded_images. For example, like the following.

const formData = new FormData();
event.target.files.forEach((image) => {
    formData.append('uploaded_images', image);
});

Hope it could help.

  • Related