1

This is my first task that I'm doing in Rest Framework.I referred a video tutorial to do this and it's weird why my validate method in serializer not working even if I totally copied the code from the video. Below is my view function:

class UserLoginAPIView(APIView):

    permission_classes = [AllowAny]
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = UserLoginSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data, status=HTTP_200_OK)  //I'm getting this response
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

and my serializer:

class UserLoginSerializer(ModelSerializer):

token = CharField(allow_blank=True, read_only=True)
username = CharField(required=False, allow_blank=True)
email = EmailField(label='Email Address', required=False, allow_blank=True)

class Meta:
    model = User
    fields = [
        'username',
        'email',
        'password',
        'token',
    ]
    extra_kwargs = {"password":
                        {"write_only": True}
                    }

    def validate(self, data):
        print("***************validating*******************")
        # user_obj = None
        email = data.get("email", None)
        username = data.get("username", None)
        password = data["password"]
        if not email and not username:
            raise ValidationError("A username or email is required to login.")
        user = User.objects.filter(
                Q(email=email) |
                Q(username=username)
            ).distinct()
        user = user.exclude(email__isnull=True).exclude(email__iexact='')
        print(user, "-------------*********************")
        if user.exists() and user.count() == 1:
            user_obj = user.first()
        else:
            raise ValidationError("This username/email is not valid.")
        if user_obj:
            if not user_obj.check_password(password):
                print("wrong pwd", "**************************************")
                raise ValidationError("Incorrect credentials! Please Try again!")
        data["token"] = "SOME RANDOM TOKEN"
        return data

As the first line in validate method not being executed, how am I getting the response(200_OK)? Please help me with this..

user10058776
  • 183
  • 1
  • 3
  • 17
  • 2
    Are you sure you are hitting the right endpoint, and that your view's post method is being called? And please show the rest of the serializer, with that validate method in context. – Daniel Roseman Dec 04 '18 at 09:36
  • 2
    Please ensure that `validate` method is a part of `UserLoginSerializer. First, delete all `*.pyc` files and try again. – Grijesh Chauhan Dec 04 '18 at 09:39

1 Answers1

4

Oh that was just a silly syntactical error. My validate method should have been in the UserLoginSerializer class and not in the Meta class.

user10058776
  • 183
  • 1
  • 3
  • 17