简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM