Django - user is_active

谁说我不能喝 提交于 2019-12-10 13:22:42

问题


This is my user authentication method:

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', {})

If user exists and is not active wrong message appears:

messages.error(request, 'Invalid username/password!')
return HttpResponseRedirect(reverse('index'))

instead of:

print('TEST')
messages.info(request, 'Inactive user')
return HttpResponseRedirect(reverse('index'))

I don't have any idea what is wrong here... Any clues?


回答1:


The default ModelBackend authentication backend started rejecting inactive users in Django 1.10. Therefore your authenticate() call returns None, and you get the Invalid username/password! message from the outer if/else statement.

As Daniel says, if you use the default ModelBackend, you no longer need to check user.is_active in your login view.

If you really want authenticate to return inactive users, then you can use AllowAllUsersModelBackend instead. If you do this, then it is your responsibility to check the is_active flag in your login view.

AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']



回答2:


The call to authenticate already checks that the user has the is_active flag set, and returns None if not. There is no need to check it separately.



来源:https://stackoverflow.com/questions/43184151/django-user-is-active

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!