码迷,mamicode.com
首页 > Web开发 > 详细

django rest 实现多图片上传

时间:2020-10-18 09:29:15      阅读:29      评论:0      收藏:0      [点我收藏+]

标签:file   svi   int   length   max   图片   mss   als   meta   

  • models 配置

    class ImageItems(models.Model):
    image = models.ImageField(upload_to=‘static/images/%Y/%m/%d‘, null=False, blank=False, verbose_name=‘图片url‘)
    
    class Meta:
        verbose_name = ‘图片集合‘
        verbose_name_plural = verbose_name

    2.serializers 配置

    class ListImgSerializer(serializers.Serializer):
    img = serializers.ListField(
        child=serializers.FileField(max_length=100000,
                                    allow_empty_file=False,
                                    use_url=True), write_only=True
    )
    img_list = serializers.ListField(
        child=serializers.CharField(max_length=1000, ), read_only=True
    )
    code = serializers.IntegerField(read_only=True)
    
    def create(self, validated_data):
        imgs = validated_data.get(‘img‘)
        images = []
        for index, url in enumerate(imgs):
            image = ImageItems.objects.create(image=url)
            imageItems = ImageItemsSerializer(image, context=self.context)
            images.append(imageItems.data[‘image‘])
        return {"img_list": images, "code": 201}
  • viewSet 配置
    class ImageItemsViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    queryset = ImageItems.objects.all()
    serializer_class = ListImgSerializer
    parser_classes = (MultiPartParser, FileUploadParser,)
  • url 自己完成了,so easy
  • postman 验证
    技术图片
  • django rest 实现多图片上传

    标签:file   svi   int   length   max   图片   mss   als   meta   

    原文地址:https://blog.51cto.com/12113362/2542178

    (0)
    (0)
       
    举报
    评论 一句话评论(0
    登录后才能评论!
    © 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
    迷上了代码!