0

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.

4
  • Because the context has no request. Commented May 6, 2020 at 18:53
  • You can debug it with pdb or pudb. pip install pudb then put this line wherever you want the break: import pudb; pudb.set_trace() Commented May 6, 2020 at 18:58
  • @WillemVanOnsem can I neglect the error ? Commented May 6, 2020 at 18:58
  • @RossRogers Thanks I will try Commented May 6, 2020 at 19:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Mr.Marker, I added the code with my views.py Why do you not recommending it ?
Because you are getting voters based on authorized user. That's quite a business logic or validation (i cant see where it is used). Best practices would be if you exclude business logic into services.py.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.