正如Django 文档所说:
如果您需要的更改纯粹是行为性的,并且不需要对存储在数据库中的内容进行任何更改,则可以创建基于 User 的代理模型。
由于您想用自定义User
模型替换它:
例如,在某些网站上,使用电子邮件地址而不是用户名作为您的标识令牌更有意义。
您需要User
通过子类化来实现自己的模型AbstractBaseUser
。这是一个包含 django 权限的示例代码:
class User(AbstractBaseUser, PermissionsMixin):
"""
A class implementing a fully featured User model with admin-compliant
permissions.
Email and password are required. Other fields are optional.
"""
email = models.EmailField(
_('Email Address'), unique=True,
error_messages={
'unique': _("A user with that email already exists."),
}
)
username = models.CharField(
_('Username'), max_length=30, unique=True, blank=True, null=True,
help_text=_('30 characters or fewer. Letters, digits and _ only.'),
validators=[
validators.RegexValidator(
r'^\w+$',
_('Enter a valid username. This value may contain only '
'letters, numbers and _ character.'),
'invalid'
),
],
error_messages={
'unique': _("The username is already taken."),
}
)
is_staff = models.BooleanField(
_('Staff Status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.')
)
is_active = models.BooleanField(
_('Active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.')
)
date_joined = models.DateTimeField(_('Date Joined'), default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'email'
class Meta(object):
verbose_name = _('User')
verbose_name_plural = _('Users')
abstract = False
def get_full_name(self):
"""
Returns email instead of the fullname for the user.
"""
return email_to_name(self.email)
def get_short_name(self):
"""
Returns the short name for the user.
This function works the same as `get_full_name` method.
It's just included for django built-in user comparability.
"""
return self.get_full_name()
def __str__(self):
return self.email
def email_user(self, subject, message, from_email=None, **kwargs):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email], **kwargs)