【问题标题】:AttributeError: 'NoneType' object has no attribute 'is_active'AttributeError:“NoneType”对象没有属性“is_active”
【发布时间】:2016-07-22 09:14:47
【问题描述】:

我正在尝试使用 Parsley.js 和 Django 设置前端用户身份验证检查。
这是我的看法

@requires_csrf_token
def password_check(request):
    email = request.POST.get('email')
    password = request.POST.get('password1')
    user = authenticate(email=email, password=password)

    if request.is_ajax():
        if user.is_active:
            res = "These password and e-mail are ok."
            ajax_vars_login = {'response': res, 'email': email, 'password': password}
            json_data_login = json.dumps(ajax_vars_login)
        else:
            res = "The e-mail or the password field aren't correct."
            ajax_vars_login = {'response': res, 'email': email, 'password': password}
            json_data_login = json.dumps(ajax_vars_login)

        return HttpResponse(json_data_login, content_type='application/json')

验证器

Parsley.addAsyncValidator(
  'emailPwCombination', function (xhr) {
       var password = $('#password').parsley();
       var email = $('#email').parsley();
       var response = xhr.responseText;
       var jsonResponse = JSON.parse(response);
       var jsonResponseText = jsonResponse["response"];

       if(jsonResponseText == 'The password and e-mail are ok.')
           return true;
       if(jsonResponseText == '404')
           return false;
  }, '/password_check/'
);

但是当调用“password_check”函数时,我得到这个错误:
AttributeError at /password_check/
“NoneType”对象没有“is_active”属性

我尝试在“request.is_ajax()”之后放置 print 来测试值,它有时会捕获电子邮件,有时会捕获密码,但不会将两者放在一起。

我该如何解决这个问题?

【问题讨论】:

  • 它告诉您authenticate 没有返回任何内容,可能是因为电子邮件和密码不匹配。你应该检查一下。

标签: javascript django django-authentication parsley.js nonetype


【解决方案1】:

使用django的authenticate函数时,只有认证成功时才会返回用户对象。

当提供不正确的凭据时,authenticate 返回None。这就是您收到AttributeError 的原因。

要解决此问题,请为用户添加额外的检查,如下所示:

if user and user.is_active:

这样,用户的is_active属性只有在用户存在时才会被检查。

【讨论】:

  • 我不再得到 AttributeError - 并且该函数被正确调用 - 但我仍然无法同时获取两个值:总是一个或另一个。
  • 你在说哪些价值观?
  • “电子邮件”和“密码”
  • 是这样的:{password: "password", response: "The e-mail or the password field are not correct.", email: null}
  • 电子邮件值似乎是null。您确定电子邮件已正确发送到 django 服务器吗?你检查过浏览器网络标签中的标题吗?
猜你喜欢
  • 2014-02-04
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 2019-01-01
  • 2021-12-26
  • 2019-07-23
相关资源
最近更新 更多