It's hard for me to spend time with the Django Rest Framework to upload multiple images. What I want is a rental table in which the user will fill in the rental information along with several images at the same time (the images may look like a kitchen, living room, bathroom, etc.) for the rental that they want to register. A single rental can have multiple images, so I have an image field with many relationships. I could not send multiple images to the server or api. Only one image that is used for storage on the server, but after changing my database design and switching to the ManyToManyField option, even one image will not be saved.
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media')
Models.py
class Gallery(models.Model): image = models.FileField(null=True,blank=True,upload_to='upload/') class Meta: verbose_name = _('Gallery') verbose_name_plural = _('Galleries') class Rental(models.Model): listingName = models.CharField(_("Lisitng Name"), max_length=255, blank=False, null=True, help_text=_("Title of the rental space")) property = models.CharField(_("Property type"),max_length=10,null=True) room = models.PositiveIntegerField(_("No of Rooms"), blank=False, null=True, help_text=_("Number of bedrooms available")) price = models.PositiveIntegerField(blank=False,null=True) city = models.CharField(_("City"), max_length=255, blank=False, null=True) image = models.ManyToManyField(Gallery)
Serializers.py
class GallerySerializer(serializers.ModelSerializer): class Meta: model = Gallery fields=('pk','image') class RentalSerializer(serializers.ModelSerializer): image = GallerySerializer(many=True) class Meta: model = Rental fields = ('pk','listingName','property','city','room','price','image') def create(self,validated_data): listingName=validated_data.get('listingName',None) property=validated_data.get('property',None) city=validated_data.get('city',None) room=validated_data.get('room',None) price=validated_data.get('price',None) image=validated_data.pop('image') return Rental.objects.create(listingName=listingName,property=property,city=city, room=room,price=price,image=image)
Views.py
class FileUploadView(APIView): parser_classes = (FileUploadParser, ) def post(self, request, format=None): uploaded_file = request.FILES['file'] print('up_file is',uploaded_file) with open('/media/upload/'+uploaded_file.name, 'wb+') as destination: for chunk in uploaded_file.chunks(): print('chunk',chunk) destination.write(chunk) destination.close() return Response(uploaded_file.name, status.HTTP_201_CREATED) class RentalList(generics.ListCreateAPIView): serializer_class = RentalSerializer queryset = Rental.objects.all() def get(self,request,format=None): rental = self.get_queryset() serializer_rental = RentalSerializer(rental,many=True) return Response(serializer_rental.data) @permission_classes((IsAdminUser, )) def post(self,request,format=None): user=request.user serializer_rental = RentalSerializer(data=request.data,context={'user':user}) if serializer_rental.is_valid(): serializer_rental.save() return Response(serializer_rental.data,status=status.HTTP_201_CREATED) return Response(serializer_rental.errors,status=status.HTTP_400_BAD_REQUEST) class RentalDetail(generics.RetrieveUpdateDestroyAPIView): queryset=Rental.objects.all() serializer_class = RentalSerializer
The front part for sending multiple images at once
onDrop(files) { console.log('Received files: ', files); this.setState({ files: files }); var image = new FormData(files); console.log('formdata image',image); var multiple_image = files; console.log('multiple_image',multiple_image); $.each(multiple_image,function(i,file){ image.append('image_'+i,file); }); console.log('images are',image); $.ajax({ url:'http://localhost:8000/api/upload/', data:image, contentType:false, processData:false, type:'POST', mimeType: "multipart/form-data", }); }
The payload request on the console shows all the images. What could be the problem? What I did wrong?