【问题标题】:django api how upload multiple imagesdjango api如何上传多张图片
【发布时间】:2021-02-27 03:15:00
【问题描述】:

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

我是我的模特

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

我的类视图处理 post 请求,我尝试使用用户方法 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 不给我循环,不管我发送多少张图片

【问题讨论】:

    标签: python django api django-rest-framework


    【解决方案1】:

    我收到此错误消息:AttributeError: 'PropertyImageSerializers' 对象没有属性“属性”但我的模型你可以看到我有 属性

    property 不是PropertyImageSerializers 类的属性,这就是AttributeError 的原因

    我想你会找到答案here

    更新:

    你可以这样做

    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)
    

    【讨论】:

    • 我改变了一点,for 不起作用我可以发送很多图像但我没有循环
    • @JúniorOaks 你这样做的方式,post 函数可能会在第一次迭代之后返回响应,这不是所需的行为,对吧?您应该在成功处理完所有图像后返回响应。
    • 谢谢@md nasfis khan,你说得对,我没有用新图像将值附加到列表中,谢谢,正在运行 100%
    猜你喜欢
    • 2020-12-05
    • 2017-09-09
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    相关资源
    最近更新 更多