Can't move validation from view to serializer

I need to move validation from to How can I do it?

Validation must check:

  1. user can't follow himself
  2. user can't follow author that his already follow

I have a ViewSet with @action:




        methods=['post', 'delete'], 



    def subscribe(self, request, id=None): 


        author_id = id 

        if request.method == 'POST': 

            author = get_object_or_404(CustomUser, id=author_id) 

            if author == request.user: 

                raise serializers.ValidationError( 

                    {'errors': 'You can't follow yourself.'} 


            if self.request.user.follower.filter(author=author).exists(): 

                raise serializers.ValidationError( 

                    {'errors': 'You already follow this author.'} 


            author = get_object_or_404(CustomUser, id=author_id) 


                user=request.user, author=author 


            serializer = FollowSerializer(author, context={'request': request}) 

            return Response(, status=status.HTTP_201_CREATED) 

        if request.method == 'DELETE': 

            user_id = 

            subscribe = get_object_or_404( 

                Follow, user__id=user_id, author__id=author_id 



            return Response(status=status.HTTP_204_NO_CONTENT) 

and I have a FollowSerializer in


class FollowSerializer(serializers.ModelSerializer): 

    class Meta: 

        model = CustomUser 

        fields = ('email', 'id', 'username', 'first_name', 

                  'last_name', 'is_subscribed', 'recipes', 'recipes_count') 

I try to add a validate method like def validate(self, data): but it doesn't work.

Back to Top