本文介绍了如何使用 DJango Rest Framework 上传多个图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下代码上传单个图像.如果我选择多张图片,则只会上传所选图片中的最后一张图片.

模型.py

I am able to upload a single image with the following code. If I select multiple images then only the last image among the selected image is getting uploaded.

models.py

class Image(models.Model):
property_id = models.ForeignKey(
                'properties.Address',
                null=False,
                default=1,
                on_delete=models.CASCADE
            )
image = models.ImageField(upload_to=directory_path)

serializers.py

serializers.py

class ImageSerializer(serializers.ModelSerializer):
class Meta:
    model = Image
    fields = (
        'property_id',
        'image'
    )

views.py

views.py

class ImageView(APIView):
parser_classes = (MultiPartParser, FormParser)

def get(self, request):
    all_images = Image.objects.all()
    serializer = ImageSerializer(all_images, many=True)
    return JsonResponse(serializer.data, safe=False)

def post(self, request, *args, **kwargs):
    file_serializer = ImageSerializer(data=request.data)
    if file_serializer.is_valid():
        file_serializer.save()
        return Response(file_serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)


我对 Django 有点陌生.我想遍历在 request.data 中收到的图像数组 谁能告诉我该怎么做?


I am a little new to Django. I want to loop over my array of images which is received in the request.data Can anyone tell me how to do it?

推荐答案

所以我终于找到了一种解决方法,以自己的方式回归基础,因为我没有找到任何以 DRF 方式完成的方法.我希望这个答案对 Django 社区有所帮助.我保持我的模型和序列化器相同,更改视图以迭代每个图像并使用序列化器保存它.

So I finally got a workaround in my own way falling back to the basics as I didn't find any way to do it in a DRF way. I hope this answer is helpful to the Django community. I kept my model and serializers same changing the views to iterate over every image and save it using the serializer.

views.py

class ImageView(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def get(self, request):
        all_images = Image.objects.all()
        serializer = ImageSerializer(all_images, many=True)
        return JsonResponse(serializer.data, safe=False)

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

        # converts querydict to original dict
        images = dict((request.data).lists())['image']
        flag = 1
        arr = []
        for img_name in images:
            modified_data = modify_input_for_multiple_files(property_id,
                                                            img_name)
            file_serializer = ImageSerializer(data=modified_data)
            if file_serializer.is_valid():
                file_serializer.save()
                arr.append(file_serializer.data)
            else:
                flag = 0

        if flag == 1:
            return Response(arr, status=status.HTTP_201_CREATED)
        else:
            return Response(arr, status=status.HTTP_400_BAD_REQUEST)

helpers.py

def modify_input_for_multiple_files(property_id, image):
    dict = {}
    dict['property_id'] = property_id
    dict['image'] = image
    return dict

models.py

class Image(models.Model):
    property_id = models.ForeignKey(
                    'properties.Address',
                    null=False,
                    default=1,
                    on_delete=models.CASCADE
                )
    image = models.ImageField(upload_to=directory_path)

serializers.py

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = (
            'property_id',
            'image'
        )

请求以 querydict 的形式出现.images = dict((request.data).lists())['image'] 行将查询 dict 转换为 python dict,然后循环遍历 'image'键.

The request comes in the form of querydict. The line images = dict((request.data).lists())['image'] coverts query dict to python dict and then looping over the array under the 'image' key.

邮递员请求如下:

这篇关于如何使用 DJango Rest Framework 上传多个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 20:43