django休息框架,用于多个图像上传

时间:2022-04-05 03:40:47

I am having difficult time with Django Rest Framework for multiple image upload.What i want is, there is a rental table where user will fill about rental information along with multiple images at once(images can be like kitchen,living room,bathroom etc) for that rent they want to register. one rent can have multiple images,so i have image field with manytomany relation.I could not able to send multiple images to server or api. Only one image used to get stored on the server but after changing my database design and going to the ManyToManyField option even a single image won't get stored.

我很难用Django Rest Framework进行多个图像上传。我想要的是,有一个租赁表,用户可以一次填写租赁信息和多个图像(图像可以像厨房,客厅,浴室等)对于他们想要注册的租金。一个租金可以有多个图像,所以我有多个关系的图像字段。我无法向服务器或api发送多个图像。只有一个图像用于存储在服务器上但在更改我的数据库设计并转到ManyToManyField选项后,即使单个图像也不会被存储。

settings.py

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

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

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

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

Frontend part for sending multiple image 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",
           });
        }

Request payload on the console shows all the images.What might be the issue? What have i done wrong?

控制台上的请求有效负载显示所有图像。可能是什么问题?我做错了什么?

1 个解决方案

#1


0  

I think you would have missed MEDIA_URL and MEDIA_ROOT in settings.py file. If you have missed or misconfigured it, django would place the file in some other location out of your project depending on your OS (for me django placed the file in /home/username/) . Check whether there is any such folder in your computer.

我想你会在settings.py文件中遗漏MEDIA_URL和MEDIA_ROOT。如果您错过了或配置错误,django会根据您的操作系统将文件放在项目的其他位置(对我而言,django将文件放在/ home / username /中)。检查计算机中是否有此类文件夹。

If you have configured MEDIA_URL and MEDIA_ROOT in settings.py please update them the question.

如果您在settings.py中配置了MEDIA_URL和MEDIA_ROOT,请更新问题。

#1


0  

I think you would have missed MEDIA_URL and MEDIA_ROOT in settings.py file. If you have missed or misconfigured it, django would place the file in some other location out of your project depending on your OS (for me django placed the file in /home/username/) . Check whether there is any such folder in your computer.

我想你会在settings.py文件中遗漏MEDIA_URL和MEDIA_ROOT。如果您错过了或配置错误,django会根据您的操作系统将文件放在项目的其他位置(对我而言,django将文件放在/ home / username /中)。检查计算机中是否有此类文件夹。

If you have configured MEDIA_URL and MEDIA_ROOT in settings.py please update them the question.

如果您在settings.py中配置了MEDIA_URL和MEDIA_ROOT,请更新问题。