我是一名学习Django Rest Framework的学生
我尝试使用form-data上传多个文件
当我发送类似于Postman中的请求时
就会出现错误,以下是错误信息
images_data = self.context.get('request').request.FILES
AttributeError: 'NoneType' object has no attribute '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
我已经看过这个链接了:https://codeday.me/en/qa/20190306/12057.html。感谢您的帮助。