django - 为什么authenticate() 为非事件用户返回None?

标签 django authentication login django-custom-user

我有 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 是:
        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对于非活跃用户?

搜索后我发现了更有趣的问题 user.is_authenticated always returns False for inactive users on template 但没有找到适合我情况的答案

最佳答案

首先,请注意 Django 带有 login viewauthentication form当非事件用户尝试登录时,它会显示合适的错误消息。如果您使用它们,那么您可能不必更改 authenticate() 的行为。 .

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

如果你想允许非事件用户登录,那么你可以使用AllowAllUsersModelBackend后端。

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

is_active 文档了解更多信息,

关于django - 为什么authenticate() 为非事件用户返回None?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49553511/

相关文章:

python - Django 头像类不起作用

Android 使用 AccountManager 添加帐户

asp.net - 如何在不使用 MembershipProvider 的情况下使用 ASP.NET 登录控件?

使用 SourceTree 登录 Git 失败,想改为使用 SSH 创建登录

python - ValueError at/image/Tensor Tensor ("activation_5/Softmax:0", shape=(?, 4), dtype=float32) 不是这个图的元素

python - 保存产品和公司后立即保存它们

python - 为 Django URL Dispatcher 编写的测试不起作用

node.js - 如何从头开始创建使用 API 进行身份验证的 SAML IDP

java - 使用 Spring Security 无需授权的预认证

php - 使用存储在 cookie 中的 session ID 自动登录