Django中authenticate()为何对非活跃用户返回None?
authenticate() return None for inactive users? Great question! The short answer is that Django's default authentication backend (ModelBackend) automatically rejects inactive users—meaning any user where is_active=False won't pass the authentication check, so authenticate() returns None.
Let me break this down specifically for your setup:
- Django's built-in
ModelBackend(the default one used unless you specify a custom backend) includes a check in itsauthenticate()method: it only returns a user object if the user'sis_activefield isTrue. Even if the username and password match an existing user, ifis_activeisFalse, the backend immediately returnsNone. - In your
CustomUsermodel, you’ve setis_active = models.BooleanField(default=False). That means every new registered user starts as inactive. When you callauthenticate()in yourUserLoginfunction, even if the provided credentials are correct, the backend sees the inactive status and bails out withNone.
If you need to allow inactive users to authenticate (though this is generally not recommended for security), you can create a custom backend that skips the is_active check. Here’s a quick example:
from django.contrib.auth.backends import ModelBackend from .models import CustomUser class AllowInactiveUsersBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = CustomUser.objects.get(username=username) if user.check_password(password): return user # No is_active check here except CustomUser.DoesNotExist: return None
Then update your settings.py to use this backend:
AUTHENTICATION_BACKENDS = [ 'your_app_name.backends.AllowInactiveUsersBackend', # Keep the default backend if you still need it for other cases # 'django.contrib.auth.backends.ModelBackend', ]
That said, if your is_active=False default is for a workflow like email verification or admin approval, the better practice is to activate the user’s account first (e.g., after they click a verification link) before letting them log in. This keeps your system secure by only allowing verified/approved users to access it.
内容的提问来源于stack exchange,提问作者dan

