Django - 用户is_active

jun*_*mek 6 django django-authentication

这是我的用户身份验证方法:

def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)

        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('index'))
            else:
                print('TEST')
                messages.info(request, 'Inactive user')
                return HttpResponseRedirect(reverse('index'))
        else:
            messages.error(request, 'Invalid username/password!')
        return HttpResponseRedirect(reverse('index'))
    else:
        return render(request, 'mainapp/login.html', {})
Run Code Online (Sandbox Code Playgroud)

如果用户存在且未激活,则会显示错误消息:

messages.error(request, 'Invalid username/password!')
return HttpResponseRedirect(reverse('index'))
Run Code Online (Sandbox Code Playgroud)

代替:

print('TEST')
messages.info(request, 'Inactive user')
return HttpResponseRedirect(reverse('index'))
Run Code Online (Sandbox Code Playgroud)

我不知道这里有什么问题......有什么线索吗?

Ala*_*air 17

默认的ModelBackend身份验证后端开始拒绝Django 1.10中的非活动用户.因此,您的authenticate()呼叫将返回None,并且您将收到无效的用户名/密码!来自外部if/else语句的消息.

正如丹尼尔所说,如果您使用默认值ModelBackend,则不再需要签user.is_active入登录视图.

如果您确实想要authenticate返回非活动用户,则可以使用AllowAllUsersModelBackend.如果您这样做,那么您有责任is_active在登录视图中检查该标志.

AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']
Run Code Online (Sandbox Code Playgroud)


Dan*_*man 6

调用authenticate已经检查用户是否设置了is_active标志,如果没有则返回None.无需单独检查.

  • 然后我如何检查用户是否存在但是不活动? (2认同)
  • 在django 1.9中,``authenticate''不会检查``user.is_active'',但是在django 2.1中会自动检查。参见[django 1.9 doc](https://docs.djangoproject.com/en/1.9/ref/contrib/auth/#django.contrib.auth.models.User.is_active)和[django 2.1 doc](https:/ /docs.djangoproject.com/en/2.1/ref/contrib/auth/#django.contrib.auth.models.User.is_active) (2认同)