如何使用Django rest\u auth创建自定义登录视图?

2024-04-26 21:50:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用django-rest-auth包创建一个带有phon号码的自定义登录名API。我只是在代码中使用rest_auth.views.LoginView来生成令牌以进行令牌身份验证

这是我的序列化程序:

class LoginUserSerializer(serializers.Serializer):
    phone = serializers.CharField()
    password = serializers.CharField(
        style={'input_type': 'password'}, trim_whitespace=False)

    def validate(self, attrs):
        phone = attrs.get('phone')
        password = attrs.get('password')

        if phone and password:
            if User.objects.filter(phone=phone).exists():
                user = authenticate(request=self.context.get('request'),
                                    phone=phone, password=password)

            else:
                msg = {'detail': 'Phone number is not registered.',
                       'register': False}
                raise serializers.ValidationError(msg)

            if not user:
                msg = {
                    'detail': 'Unable to log in with provided credentials.', 'register': True}
                raise serializers.ValidationError(msg, code='authorization')

        else:
            msg = 'Must include "username" and "password".'
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs

这是我的观点:

 from rest_auth.views import LoginView as RestLoginView

class Login(RestLoginView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, *args, **kwargs):
        serializer = LoginUserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        login(request, user)
        return super().post(request, format=None)

当我运行服务器时,我有这个页面,我不想有用户名和电子邮件字段。我要的不是这些,而是电话号码。我怎样才能解决这个问题

enter image description here


Tags: selfauthrestgetifrequestphonemsg