Why authenticate() return None for inactive users?

别说谁变了你拦得住时间么 提交于 2019-12-31 03:48:06

问题


I have CustomUser like following :

        class CustomUser(AbstractBaseUser, PermissionsMixin):
            email = models.EmailField(max_length=100, unique=True)
            username = models.CharField(max_length=20, unique=True)
            is_active = models.BooleanField(default=False)
            is_staff = models.BooleanField(default=False)
            ...

which is active default=False After user registration automatically handle UserLogin def which is :

        def UserLogin(request):
            if request.POST:
                username = request.POST['username']
                user = authenticate(username=username, password=request.POST['password'])
                print('user :', user)  # which is print None if user inactive 
                if user is not None:
                    print('is user active:', user.is_active)   # should print True or False  
                    if user.is_active:
                        login(request, user)
                        ... 
                    else:  # handle user inactive
                        ...
                else:  # for None user 
                   ...

I still trying understanding why authenticate return None for inactive users ?

After searching I found smilier issue user.is_authenticated always returns False for inactive users on template But didn't find an answer for my situation


回答1:


Firstly, note that Django comes with a login view and authentication form which display suitable error messages when inactive users try to log in. If you use them, then you probably don't have to change the behaviour for authenticate().

Since Django 1.10, the default ModelBackend authentication backend does not allow users with is_active = False to log in.

If you want to allow inactive users to log in, then you can use the AllowAllUsersModelBackend backend.

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

See the is_active docs for more info,



来源:https://stackoverflow.com/questions/49553511/why-authenticate-return-none-for-inactive-users

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