首页 > 解决方案 > django api如何上传多张图片

问题描述

我试了很多次,但我只注册了最后一个

我是我的模特

class PropertyImage(models.Model):
    property = models.ForeignKey(Property, default=None, on_delete=models.CASCADE,)
    images = models.ImageField(upload_to=upload, null=True, blank=True)

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

串行器

class PropertyImageSerializers (serializers.ModelSerializer):
    class Meta:
        model = PropertyImage
        #fields =('name','')
        fields = '__all__'

我的类视图处理程序发布请求,我尝试使用用户方法 FOR 循环所有图像并保存

看法

        def post(self, request, *args, **kwargs):
        property_id = request.data['property']
        form_data = {}

        for images in request.FILES.getlist('images'):

            form_data['property']= property_id
            form_data['images']=images

            print(form_data)

            serializer = PropertyImageSerializers(data=form_data)

            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

for 不给我循环,不管我发送多少张图片

标签: pythondjangoapidjango-rest-framework

解决方案


我收到此错误消息: AttributeError: 'PropertyImageSerializers' object has no attribute 'property' 但我的模型你可以看到我有这个属性

property不是PropertyImageSerializers类的属性,这就是为什么AttributeError

我想你会在这里找到你的答案

更新:

你可以这样做

def post(self, request, *args, **kwargs):
    property_id = request.data['property']
    form_data = {}
    form_data['property']= property_id
    success = True
    response = []
    for images in request.FILES.getlist('images'):
        form_data['images']=images
        print(form_data)
        serializer = PropertyImageSerializers(data=form_data)
        if serializer.is_valid():
            serializer.save()
            response.append(serializer.data)
        else:
            success = False
    if success:
        return Response(response, status=status.HTTP_201_CREATED)
    return Response(response,status=status.HTTP_400_BAD_REQUEST)

推荐阅读