django rest framework 在序列化程序创建方法中获取请求

django rest framework get request in serializer create method

我是一名学习 django rest 框架的学生

我尝试使用表单数据上传多个文件

当我在邮递员中发送这样的请求时

enter image description here

发生错误,这是错误消息

images_data = self.context.get('request').request.FILES

AttributeError: 'NoneType' 对象没有属性 'request'

这是模特

class Post(models.Model):
    text = models.CharField(max_length=5000)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

class Image(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    image = models.FileField(blank=True)

和浏览量

class AddPost(APIView):
    serializer_class = PostSerializer

    def post(self, request, format=None):
        serializer = PostSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return JsonResponse({'status':status.HTTP_200_OK, 'message':"sucess", 'data':""})

序列化程序

class FileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = '__all__'

class PostSerializer(serializers.ModelSerializer):
    images = FileSerializer(source='image_set', many=True, read_only=True)

    class Meta:
        model = Post
        fields = ('id', 'text', 'owner', 'created_at', 'images')

    def create(self, validated_data):
        images_data = self.context.get('request').request.FILES         
        images_data = self.context.get('request').request.FILES
        post = Post.objects.create(text=validated_data.get('text'),owner=validated_data.get('owner'))
        for image_data in images_data.values():
            Image.objects.create(post=post, image=image_data)
        return post

我已经看过这个link https://codeday.me/en/qa/20190306/12057.html

感谢您的帮助

只需将上下文传递给 views.py

中的序列化程序
PostSerializer(data=request.data, context={'request': request})

然后你就可以在serializers.py

的上下文中得到请求
self.context.get('request')