Django-尽管有AUTHENTICATION_BACKENDS,身份验证仍未返回

时间:2019-06-06 19:01:37

标签: python django

我尝试使用LoginView类进行登录。我无法登录。它总是说我的密码是错误的,但不是(我用check_password()进行了检查)。我已经在我的settings.py中设置了AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']

这是我的自定义clean中的AuthenticationForm函数:

def clean(self):
    cleaned_data = self.cleaned_data
    username = cleaned_data.get("username")
    password = cleaned_data.get("password")

    user = authenticate(username=username, password=password)

    print(user)
    print(username)
    print(password)

    try:
        us = User.objects.get(username=username)
        print(us)
        print(us.check_password(password)) # This returns True!!!
    except ObjectDoesNotExist:
        pass

    if user is not None:
        if not user.is_active:
            raise forms.ValidationError("Dieser Account ist deaktiviert. Du kannst ihn über deine E-Mail aktivieren.")
    else:
        raise forms.ValidationError("Falsches Passwort")
    return cleaned_data

1 个答案:

答案 0 :(得分:1)

ModelBackend身份验证方法可以做到这一点:

 def authenticate(self, request, username=None, password=None, **kwargs):
    if username is None:
        username = kwargs.get(UserModel.USERNAME_FIELD)
    try:
        user = UserModel._default_manager.get_by_natural_key(username)
    except UserModel.DoesNotExist:
        # Run the default password hasher once to reduce the timing
        # difference between an existing and a nonexistent user (#20760).
        UserModel().set_password(password)
    else:
        if user.check_password(password) and self.user_can_authenticate(user):
            return user

user_can_authenticate是:

  def user_can_authenticate(self, user):
        """
        Reject users with is_active=False. Custom user models that don't have
        that attribute are allowed.
        """
        is_active = getattr(user, 'is_active', None)
        return is_active or is_active is None

您的用户是否将is_active设置为True?