如何在Django Rest框架中上传多个文件

在Django rest框架中,我可以使用danialfarid / ng-file-

upload上传单个文件

views.py:

class PhotoViewSet(viewsets.ModelViewSet):

serializer_class = PhotoSerializer

parser_classes = (MultiPartParser, FormParser,)

queryset=Photo.objects.all()

def perform_create(self, serializer):

serializer.save(blogs=Blogs.objects.latest('created_at'),

image=self.request.data.get('image'))

serializers.py:

class PhotoSerializer(serializers.ModelSerializer):

class Meta:

model = Photo

models.py:

class Photo(models.Model):

blogs = models.ForeignKey(Blogs, related_name='blogs_img')

image = models.ImageField(upload_to=content_file_name)

当我尝试上传多个文件时。我进去

chrome开发人员工具:请求有效负载

------WebKitFormBoundaryjOsYUxPLKB1N69Zn

Content-Disposition: form-data; name="image[0]"; filename="datacable.jpg"

Content-Type: image/jpeg

------WebKitFormBoundaryjOsYUxPLKB1N69Zn

Content-Disposition: form-data; name="image[1]"; filename="datacable2.jpg"

Content-Type: image/jpeg

响应:

{"image":["No file was submitted."]}

我不知道如何编写用于上传多个文件的序列化程序。任何身体都请帮忙。

提前致谢

回答:

我设法解决了这个问题,希望对社区有所帮助

serializers.py:

class FileListSerializer ( serializers.Serializer ) :

image = serializers.ListField(

child=serializers.FileField( max_length=100000,

allow_empty_file=False,

use_url=False )

)

def create(self, validated_data):

blogs=Blogs.objects.latest('created_at')

image=validated_data.pop('image')

for img in image:

photo=Photo.objects.create(image=img,blogs=blogs,**validated_data)

return photo

class PhotoSerializer(serializers.ModelSerializer):

class Meta:

model = Photo

read_only_fields = ("blogs",)

views.py:

class PhotoViewSet(viewsets.ModelViewSet):

serializer_class = FileListSerializer

parser_classes = (MultiPartParser, FormParser,)

queryset=Photo.objects.all()

以上是 如何在Django Rest框架中上传多个文件 的全部内容, 来源链接: utcz.com/qa/406504.html

回到顶部