首页 > 解决方案 > 如何在 django 的用户表中重命名 is_active?

问题描述

这是我的用户模型:

class User(AbstractUser):
    id = models.AutoField(
        verbose_name="ID", serialize=False, auto_created=True, primary_key=True
    )
    email = models.EmailField(_("email address"), max_length=255, unique=True)
    avatar = models.CharField(_("avatar"), max_length=128, default="")
    username = None

    EMAIL_FIELD = "email"
    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

现在,我需要重命名is_activeactive. 本来想取消is_active之类的username,然后新建一个active字段

is_active = None
active = models.BooleanField(_("active"), default=False)

这似乎不起作用,我收到一条错误消息

 (admin.E116) The value of 'list_filter[2]' refers to 'is_active', which does not refer to a Field.

标签: pythondjango

解决方案


我不建议删除或重命名内置字段,因为您无疑会收到更多类似于您已经看到的错误消息。如果您不打算使用它,您可以将其默认为某个值(例如,username字段可以默认为电子邮件地址)。

如果要引用已存在的字段,还可以创建属性字段。这可能适用于您的active领域。is_active这种方法的唯一问题是,如果您想更改 的值,您仍然需要更新active

class User(AbstractUser):

    ...

    def __str__(self):
        return self.email

    @property
    def active(self):
        return self.is_active

推荐阅读