Anoop K George
Anoop K George

Reputation: 1735

Django Rest Framework, getting error : 'NoneType' object has no attribute

I created a blog where people can do Post,comment and likes to post. When I POST new posts I get error AttributeError at /api/posts/ 'NoneType' object has no attribute 'user' ,error occur at serializers.py in get_user_has_voted, line 20.

even though I get error , I am able to POST data and all other functionalities works fine.

Why does the error happens ? How can I debug it ?

SERIALIZER.PY

class PostSerializers(serializers.ModelSerializer):
    comments = serializers.HyperlinkedRelatedField(many=True,read_only=True,view_name = 'comment_details')
    likes_count = serializers.SerializerMethodField()
    user_has_voted = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = '__all__'
        #exclude=('voters',)

    def get_likes_count(self, instance):
        return instance.voters.count()

    def get_user_has_voted(self, instance):
        request = self.context.get("request")
        return instance.voters.filter(pk=request.user.pk).exists()  # line 20

MODELS.PY

class Post(models.Model):
    title = models.CharField(max_length=60)
    body = models.CharField(max_length=60)
    file = models.FileField(null=True,blank=True)
    voters = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                    related_name="votes",null=True,blank=True)

There are duplicate questions in Stack overflow but with different scenarios, as a begginer I couldn't grasp the idea.

Upvotes: 0

Views: 2655

Answers (1)

Tigran
Tigran

Reputation: 674

You need to pass your request to serializer via context.

serializer = PostSerializers(instance, context={'request': request})

In any case, I strongly DO NOT RECOMMEND doing that. Serializers are to serialize data, not for your business logic or validation.

Consider excluding it in services.py if it is part of your business logic.

Upvotes: 1

Related Questions