Django Rest Framework 多文件上传

多文件上传是常用需求的一个,但是DRF我是找半天都没有找到,我....

stackoverflow上面找到一个半成品,文件是可以上传的,但是返回的结果仅仅是图片的名字,并没有全路径,不过修改之后就可以了。

修改如下
# model

class Image(BaseModel):
    user = models.ForeignKey(User, verbose_name='用户')
    url = 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
#serializer

class BlogImgSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    def __str__(self):
        return self.url

    class Meta:
        model = Image
        fields = ('user', 'url')


class BlogListImgSerializer(serializers.Serializer):
    imgs = serializers.ListField(
        child=serializers.FileField(max_length=100000,
                                    allow_empty_file=False,
                                    use_url=True),write_only=True
    )
    blog_imgs = serializers.ListField(
        child=serializers.CharField(max_length=1000,),read_only=True
    )

    def create(self, validated_data):
        imgs = validated_data.get('imgs')
        images = []
        for index, url in enumerate(imgs):
            image = Image.objects.create(url=url, user=User.objects.get(id=self.context['request'].user.id))
            blog = BlogImgSerializer(image, context=self.context)
            images.append(blog.data['url'])
        return {'blog_imgs':images}
# viewset

class BlogImgViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    '''
    create:
    创建图片
    '''

    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)
    queryset = Image.objects.all()
    serializer_class = BlogListImgSerializer

    parser_classes = (MultiPartParser, FileUploadParser,)

    def get_permissions(self):
        permission_classes = [IsAuthenticated, IsOwnerOrReadOnly]
        return [premission() for premission in permission_classes]

酱紫就可以了

结果
Django Rest Framework 多文件上传_第1张图片
QQ截图20180420111026.png

你可能感兴趣的:(Django Rest Framework 多文件上传)