【问题标题】:Ignore `is_active` filed for custom user model忽略自定义用户模型的“is_active”文件
【发布时间】:2021-08-09 09:56:43
【问题描述】:

我正在尝试制作自定义用户模型,而不是几个布尔列,我将根据一个 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

【问题讨论】:

  • 你在尝试登录 django admin 吗?
  • @Amin - 不。在这种情况下我不使用 django admin
  • @Amin: 异常可能是由AuthenticationForm:github.com/django/django/blob/…引发的

标签: python django django-3.1


【解决方案1】:

你可以用属性替换is_active,所以:

class MyUser(AbstractUser):
    # …
    # no is_active field
    # …
    @property
    def is_active(self):
        return self.status > 0

【讨论】:

  • 是的,但在这种情况下,is_active 列将保留在用户表中。我正在尝试仅通过 status 列管理用户权限。
  • @OtoShavadze:那么根据status 字段,用户活动的确切时间是什么时候?
  • 状态何时大于0
  • @OtoShavadze:那么您可以将其设为属性。
  • @OtoShavadze:请问edit the question,因为现在问题缺少基本数据。
【解决方案2】:

正如文档在https://docs.djangoproject.com/en/3.2/ref/contrib/auth/#django.contrib.auth.models.User.has_perm 中所说:

如果您想允许非活动用户登录,您可以使用 AllowAllUsersModelBackend 或 AllowAllUsersRemoteUserBackend。在这种情况下,您还需要自定义 LoginView 使用的 AuthenticationForm,因为它拒绝非活动用户。请注意,对于非活动用户,has_perm() 等权限检查方法和 Django 管理员中的身份验证都返回 False。

所以你必须重写has_perm() 方法来忽略is_active()

【讨论】:

    猜你喜欢
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多