前言
Django 用户认证系统提供了一个内置的 User 对象,用于记录用户的用户名,密码等个人信息。对于 Django 内置的 User 模型, 仅包含以下一些主要的属性:
- username,即用户名
- password,密码
- email,邮箱
- first_name,名
- last_name,姓
对于一些网站来说,用户可能还包含有昵称、头像、个性签名等等其它属性,因此仅仅使用 Django 内置的 User 模型是不够。好在 Django 用户系统遵循可拓展的设计原则,我们可以方便地拓展 User 模型。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66class AbstractUser(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
Username and password are required. Other fields are optional.
"""
username_validator = UnicodeUsernameValidator()
username = models.CharField(
_('username'),
max_length=150,
unique=True,
help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[username_validator],
error_messages={
'unique': _("A user with that username already exists."),
},
)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=150, blank=True)
email = models.EmailField(_('email address'), blank=True)
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()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
abstract = True
def clean(self):
super().clean()
self.email = self.__class__.objects.normalize_email(self.email)
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"""Return the short name for the user."""
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""Send an email to this user."""
send_mail(subject, message, from_email, [self.email], **kwargs)
继承AbstractUser 拓展用户模型
内置的User
模型就是继承的AbstractUser
1
2
3
4
5
6
7
8
9class User(AbstractUser):
"""
Users within the Django authentication system are represented by this
model.
Username, password and email are required. Other fields are optional.
"""
class Meta(AbstractUser.Meta):
swappable = 'AUTH_USER_MODEL'
所以,如果我们继承 AbstractUser,将获得 User 的全部特性,而且还可以根据自己的需求进行拓展。
1 | class UserProfile(AbstractUser): |
这里在内置模型基础上添加了一些字段。
同时,我们继承了 AbstractUser
的内部类属性 Meta
。在这里继承 Meta 的原因是在你的项目中可能需要设置一些 Meta 类的属性值,不要忘记继承 AbstractUser.Meta 中已有的属性。
注意:一定要继承 AbstractUser
,而不是继承 auth.User
。尽管 auth.User
继承自 AbstractUser
且并没有对其进行任何额外拓展,但 AbstractUser
是一个抽象类,而 auth.User
不是。如果你继承了 auth.User
类,这会变成多表继承,在目前的情况下这种继承方式是不被推荐的。
此外,AbstractUser 类又继承自 AbstractBaseUser,前者在后者的基础上拓展了一套用户权限(Permission)系统。因此如非特殊需要,尽量不要从 AbstractBaseUser 拓展,否则你需要做更多的额外工作。
为了让 Django 用户认证系统使用我们自定义的用户模型,必须在 settings.py 里通过 AUTH_USER_MODEL
指定自定义用户模型所在的位置,即需要如下设置:1
2
3
4django_auth_example/settings.py
# 其它设置...
AUTH_USER_MODEL = 'users.User'
使用 Profile 模式拓展用户模型
如果想为一个已使用了 Django 内置 User 模型的项目拓展用户模型,上述继承 AbstractUser 的拓展方式会变得有点麻烦。Django 没有提供一套自动化的方式将内置的 User 迁移到自定义的用户模型,因为 Django 已经为内置的 User 模型生成了相关数据库迁移文件和数据库表。如果非要这么做的话,需要手工修改迁移文件和数据库表,并且移动数据库中相关的用户数据。
所以我们采用另一种不改动数据库表的方式来拓展用户模型,具体来说,我们在创建一个模型(通常命名为 Profile)来记录用户相关的数据,然后使用一对一的方式将这个 Profile 模型和 User 关联起来,就好像每个用户都关联着一张记录个人资料的表一样。代码如下:
1 | from django.contrib.auth.models import User |
这种方式和 AbstractUser 的区别是,继承 AbstractUser 的用户模型只有一张数据库表。而 Profile 这种模式有两张表,一张是 User 模型对应的表,一张是 Profile 模型对应的表,两张表通过一对一的关系关联。可见,当要查询某个用户的 Profile 时,需要执行额外的跨表查询操作,所以这种方式比起直接继承 AbstractUser 效率更低一点。因此对于新项目来说,优先推荐使用继承 AbstractUser 的方式来拓展用户模型。