忽略为自定义用户模型提交的“is_active”
Ignore `is_active` filed for custom user model
我正在尝试制作自定义用户模型,而不是几个布尔列,我将根据一个 status
字段来管理用户权限:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
class MyUser(AbstractUser):
username = None
is_staff = None
is_superuser = None
is_active = None
email = models.EmailField(_('email address'), unique=True)
status = models.PositiveSmallIntegerField(default=0)
在 settings.py
文件中添加:
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']
然后,当尝试登录时,出现错误:This account is inactive.
如何忽略为我的自定义用户模型提交的 is_active
?
您可以将 is_active
替换为 属性,因此:
class MyUser(AbstractUser):
# …
# no is_active field
# …
@property
def <b>is_active</b>(self):
return self.status > 0
正如文档在 https://docs.djangoproject.com/en/3.2/ref/contrib/auth/#django.contrib.auth.models.User.has_perm 中所说:
You can use AllowAllUsersModelBackend or AllowAllUsersRemoteUserBackend if you want to allow inactive users to login. In this case, you’ll also want to customize the AuthenticationForm used by the LoginView as it rejects inactive users. Be aware that the permission-checking methods such as has_perm() and the authentication in the Django admin all return False for inactive users.
所以你必须覆盖 has_perm()
方法来忽略 is_active()
我正在尝试制作自定义用户模型,而不是几个布尔列,我将根据一个 status
字段来管理用户权限:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
class MyUser(AbstractUser):
username = None
is_staff = None
is_superuser = None
is_active = None
email = models.EmailField(_('email address'), unique=True)
status = models.PositiveSmallIntegerField(default=0)
在 settings.py
文件中添加:
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']
然后,当尝试登录时,出现错误:This account is inactive.
如何忽略为我的自定义用户模型提交的 is_active
?
您可以将 is_active
替换为 属性,因此:
class MyUser(AbstractUser):
# …
# no is_active field
# …
@property
def <b>is_active</b>(self):
return self.status > 0
正如文档在 https://docs.djangoproject.com/en/3.2/ref/contrib/auth/#django.contrib.auth.models.User.has_perm 中所说:
You can use AllowAllUsersModelBackend or AllowAllUsersRemoteUserBackend if you want to allow inactive users to login. In this case, you’ll also want to customize the AuthenticationForm used by the LoginView as it rejects inactive users. Be aware that the permission-checking methods such as has_perm() and the authentication in the Django admin all return False for inactive users.
所以你必须覆盖 has_perm()
方法来忽略 is_active()