【发布时间】:2021-12-31 10:23:36
【问题描述】:
我创建了自定义用户模型。现在我想使用user_name 作为用户名字段而不是username。如下面的代码 sn-p 所示。
class CustomUser(AbstractBaseUser):
username_validator = UnicodeUsernameValidator()
user_name = models.CharField(
_('username'),
max_length=100,
unique=True,
help_text=_('Required. 100 characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[username_validator],
error_messages={
'unique': _("A user with that username already exists."),
},
)
USERNAME_FIELD = 'user_name'
我无法做到这一点。我遇到以下错误:
SystemCheckError: System check identified some issues:
ERRORS:
<class 'accounts.admin.CustomUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.CustomUser'.
<class 'accounts.admin.CustomUserAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'CustomUserAdmin', or an attribute or method on 'accounts.CustomUser'
之所以使用这个,是因为项目的所有数据库表约定都是这样的。如果我可以定义字段名称是数据库,就像我们对 Meta 类中的表所做的那样,如下所示。我将我的 customuser 模型称为 db 中的用户模型。
class Meta:
db_table = "user"
有没有这样调用表字段的方法?
class Meta:
db_table_user_name = "username"
如果可能的话,我们不需要将username 更改为user_name。我们可以直接调用用户名字段等于数据库中的用户名。当且仅当 django 模型有可能。
【问题讨论】:
标签: python django django-models abstract-class django-users