Can't move validation from view to serializer

I need to move validation from views.py to serializators.py. 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:

my view.py:

@action( 

        detail=True, 

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

        permission_classes=(permissions.IsAuthenticated,) 

    ) 

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

        """Following""" 

        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) 

            Follow.objects.create( 

                user=request.user, author=author 

            ) 

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

            return Response(serializer.data, status=status.HTTP_201_CREATED) 

        if request.method == 'DELETE': 

            user_id = request.user.id 

            subscribe = get_object_or_404( 

                Follow, user__id=user_id, author__id=author_id 

            ) 

            subscribe.delete() 

            return Response(status=status.HTTP_204_NO_CONTENT) 

and I have a FollowSerializer in serializers.py

my serializers.py

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