I have 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
return None
对于不活跃的用户?
搜索后我发现了更微笑的问题对于模板上的非活动用户,user.is_authenticated 始终返回 False https://stackoverflow.com/questions/39993714/user-is-authenticated-always-returns-false-for-inactive-users-on-template但没有找到适合我情况的答案
首先,请注意 Django 附带了登录视图 https://docs.djangoproject.com/en/2.0/topics/auth/default/#django.contrib.auth.views.LoginView and 认证表格 https://docs.djangoproject.com/en/2.0/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm当非活动用户尝试登录时,它们会显示适当的错误消息。如果您使用它们,那么您可能不必更改以下行为authenticate()
.
从 Django 1.10 开始,默认ModelBackend
身份验证后端不允许用户使用is_active = False
登录。
如果您想允许非活动用户登录,那么您可以使用AllowAllUsersModelBackend
后端。
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']
See the is_active https://docs.djangoproject.com/en/2.0/ref/contrib/auth/#django.contrib.auth.models.User.is_active文档以获取更多信息,
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)