python - 用于多张图片上传的django rest框架

标签 python ajax django django-rest-framework

我在使用 Django Rest Framework 上传多张图片时遇到了困难。我想要的是,有一个租赁表,用户可以在其中一次填写租赁信息以及多张图片(图片可以是厨房、客厅、浴室等)他们想要登记的租金。一个租金可以有多个图像,所以我有 image 字段与 manytomany 关系。我无法将多个图像发送到服务器或 api。曾经只有一张图像存储在服务器上,但在更改我的数据库设计并转到 ManyToManyField 选项后,即使是一张图像也不会存储。

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')

模型.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)

序列化器.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

一次发送多张图片的前端部分

 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",
           });
        }

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

最佳答案

我认为您可能错过了 settings.py 文件中的 MEDIA_URLMEDIA_ROOT。如果您错过或配置错误,django 会根据您的操作系统将文件放在项目之外的其他位置(对我来说,django 将文件放在 /home/username/)。检查您的计算机中是否有这样的文件夹。

如果您在 settings.py 中配置了 MEDIA_URLMEDIA_ROOT,请更新他们的问题。

关于python - 用于多张图片上传的django rest框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35009014/

相关文章:

python - 3D 图显示错误的轴标签(X 轴有 Y 轴名称,Y 轴有 X 轴名称)

javascript - 根据 URL 创建变量

ajax - 如何在ajax和laravel中传递数组和其他字段

python - Django 列表序列化器批量更新失败, 'QuerySet' 对象没有属性 'pk'

python - 如何找出哪一行代码使文件保持打开状态?

python - 嵌套函数中的局部变量

python - 如何为命令行命令设置别名? (苹果)

python - 来自 MouseReleaseEvent 的信号

javascript - AJAX 请求在 FIREFOX 上被拒绝,但在 IE 上则不然

python - 检查外键上的对象是否已设置