1

发现了很多关于它的问题,但是找不到对我有帮助的东西。Settings.py 包含身份验证后端:

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
)

和身份验证用户模型:

AUTH_USER_MODEL = 'users.User'

用户模型继承自 AbstractUser 类:

class User(AbstractUser):
   <some_fields>

然后从 User 继承了 3 类用户。我注册了客户:

class Client(User, models.Model):
    status = models.CharField(max_length=1, default='C', editable=False)
    <some_fields>

当我通过激活链接激活用户时,一切正常。客户端是经过身份验证的用户。但是,当我只是尝试通过登录名和密码输入时,身份验证总是返回无:

class LoginView(APIView):
    def post(self, request):
        qs = User.objects.filter(Q(email=request.data.get('user')) | Q(phone=request.data.get('user')))
        if qs.exists():
            username = qs.first().username
            password = request.data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return Response(CMD(user.id), status=status.HTTP_200_OK)
        return Response({
            'error': 'Invalid login / password',
        }, status=status.HTTP_400_BAD_REQUEST)

我已经记录了返回所需客户端的 qs,用户名和密码也可以,但身份验证返回无。

我认为问题可能是客户端未正确注册。这是注册表格:

class ClientSignupForm(forms.ModelForm):
    class Meta:
        model = Client
        exclude = [
            'username',
            'date_joined',
        ]

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(ClientSignupForm, self).__init__(*args, **kwargs)

    def clean(self):
        <actions to validate captcha>

    def save(self):
        username = 'user' + str(User.objects.all().aggregate(Max('id'))['id__max'] + 1)
        return Client.objects.create_user(**self.cleaned_data, username=username)
4

0 回答 0