尝试验证用户时出现类型错误

时间:2018-05-15 20:38:07

标签: django django-authentication django-custom-user

我正在尝试使用Django 2.0.4版中的自定义MyUser模型对用户进行身份验证。但是,当代码命中我的自定义后端模块中的check_password行时,我收到此错误:

Error

回溯:

    Traceback:
     File "D:\Python\lib\site-packages\django\core\handlers\exception.py" in inner
     35 response = get_response(request)

     File "D:\Python\lib\site-packages\django\core\handlers\base.py" in _get_response
     128 response = self.process_exception_by_middleware(e, request)

     File "D:\Python\lib\site-packages\django\core\handlers\base.py" in _get_response
     126 response = wrapped_callback(request, *callback_args, **callback_kwargs)

    File "d:\Programs\Python\Django\test2\accounts\views.py" in login_user
    52 user        = authenticate(request=request, email=email, password=password)

    File "D:\Python\lib\site-packages\django\contrib\auth\__init__.py" in authenticate
    70 user = _authenticate_with_backend(backend, backend_path, request, credentials)

    File "D:\Python\lib\site-packages\django\contrib\auth\__init__.py" in _authenticate_with_backend
    116 return backend.authenticate(*args, **credentials)

    File "d:\Programs\Python\Django\test2\accounts\backends.py" in authenticate
    29 if MyUser.check_password(password):

    Exception Type: TypeError at /accounts/login/
    Exception Value: check_password() missing 1 required positional argument: 'raw_password'

以下是backends.py的自定义后端:

    class EmailAuthenticationBackend(ModelBackend):
      def authenticate(self, request, email=None, password=None):
        MyUser = get_user_model()

        try:
          # Check the email/password and return a user
          user = MyUser.objects.get(email=email)

          # BUG
          if MyUser.check_password(password):
            return user

          except MyUser.DoesNotExist:
            return None

这是密码的来源。登录用户视图:

    def login_user(request):
      template_name   = 'registration/login.html'

      if request.method == 'POST':
        email       = request.POST['email']
        password    = request.POST['password']
        user        = authenticate(request=request, email=email, password=password)

虽然错误似乎有点自我解释,但我尝试过的所有组合都失败了。我已经阅读了文档并搜索了其他类似的方法:没有。

1 个答案:

答案 0 :(得分:1)

您应该在您的实例上调用该方法,而不是类。

if user.check_password(password):