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.
contexthas norequest.pip install pudbthen put this line wherever you want the break:import pudb; pudb.set_trace()