为什么authenticate()对于不活动的用户返回None? [英] Why authenticate() return None for inactive users?

查看:166
本文介绍了为什么authenticate()对于不活动的用户返回None?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有CustomUser,如下所示:

        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)
            ...

active default=False 用户注册后,将自动处理UserLogin def:

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 
                   ...

我仍在尝试理解为什么authenticate为不活动的用户返回None吗?

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

搜索后,我发现了一个更苗条的问题用户对于模板上的非活动用户,.is_authenticated始终返回False 但没有找到适合我的情况的答案

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

推荐答案

首先,请注意,Django随附了

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().

从Django 1.10开始,默认的ModelBackend身份验证后端不允许使用is_active = False的用户登录.

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

如果要允许不活动的用户登录,则可以使用AllowAllUsersModelBackend后端.

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

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

请参见 is_active 文档以获取更多信息,

See the is_active docs for more info,

这篇关于为什么authenticate()对于不活动的用户返回None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆