djangodjango-rest-frameworkdjango-serializerdjango-file-upload

django rest framework get request in serializer create method


I'm a student studying django rest framework

I tried to upload multiple file with form-data

when i send request like this in postman

enter image description here

error occurs and this is error message

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

AttributeError: 'NoneType' object has no attribute 'request'

this is model

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)

And views

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':""})

serializers

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

i already saw this link https://codeday.me/en/qa/20190306/12057.html

thanks for your help


Solution

  • Just pass context to your serializer in views.py

    PostSerializer(data=request.data, context={'request': request})
    

    And then you will be able to get request in the context in serializers.py

    self.context.get('request')