You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中authenticate()为何对非活跃用户返回None?

Why does 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 its authenticate() method: it only returns a user object if the user's is_active field is True. Even if the username and password match an existing user, if is_active is False, the backend immediately returns None.
  • In your CustomUser model, you’ve set is_active = models.BooleanField(default=False). That means every new registered user starts as inactive. When you call authenticate() in your UserLogin function, even if the provided credentials are correct, the backend sees the inactive status and bails out with None.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:49:59