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..

2
  • 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. Commented Dec 4, 2018 at 9:36
  • 2
    Please ensure that validate method is a part of UserLoginSerializer. First, delete all *.pyc` files and try again. Commented Dec 4, 2018 at 9:39

1 Answer 1

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.

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

1 Comment

Lol! So silly of you.... But wait :O I have wasted my 1 hour too because of this same issue! Thanks a lot for pointing out

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.