1

这是我在 Rest Framework 中执行的第一项任务。我参考了一个视频教程来执行此操作,这很奇怪,即使我完全复制了视频中的代码,我在序列化程序中的验证方法也不起作用。下面是我的视图功能:

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)

和我的序列化器:

类 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

作为 validate 方法的第一行没有被执行,我如何得到响应(200_OK)?请在这件事上给予我帮助..

4

1 回答 1

4

哦,那只是一个愚蠢的语法错误。我的 validate 方法应该在 UserLoginSerializer 类中,而不是在 Meta 类中。

于 2018-12-04T09:51:06.047 回答