Django1.11 AttributeError at / login /' NoneType'对象没有属性' is_active'

时间:2018-03-24 07:55:47

标签: python django

我正在用Django 1.11编写一个登录页面。不知怎的,我收到了这条消息

  

/ login /

中的AttributeError

' NoneType'对象没有属性' is_active'

我的代码如下

def login(request):

    if request.user.is_authenticated():
        return HttpResponseRedirect('/index/')

    username = request.POST.get('username', '')
    password = request.POST.get('password', '')

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

    if user is None and user.is_active:
        auth.login(request, user)
        return HttpResponseRedirect('/index/')
    else:
        return render_to_response('login.html', RequestContext(request, locals()))

这是我的模板

<!doctype html>
<body>
    <form action="" method="post">
        <label for="username">用戶名稱:</label>{% csrf_token %}
        <input type="text" name="username" value="{{username}}" id="username"><br />
        <label for="password">用戶密碼:</label>
        <input type="password" name="password" value="" id="password"><br />
        <input type="submit" value="登入" />
    </form>
</body>

3 个答案:

答案 0 :(得分:1)

您正试图在无对象上执行is_active,这就是获取错误的原因。它应该是

if user is not None and user.is_active:

因此,如果用户不是无效且活动,则登录并发送至索引页面。

答案 1 :(得分:1)

如果存在,对象返回true,因此您可以更改逻辑

if user and user.is_active

答案 2 :(得分:0)

你的逻辑被打破了。它应该是if user is not None and user.is_axtive

相关问题