User 对象( django.contrib.auth.models.User )是 Django 身份验证系统的核心,表示与 Django
应用交互的每个个体。根据 Django 文档,身份验证系统的很多方面都能用到 User 对象,例如访
问限制、注册新用户,以及网站内容与创建者之间的关系。
User 模型有 5 个主要属性:
❏ 用户账户的用户名( username )
❏ 用户账户的密码( password )
❏ 用户的电子邮件地址( email )
❏ 用户的名字( first_name )
❏ 用户的姓( last_name )
此外, User 模型还有其他属性,例如 is_active 、 is_staff 和 is_superuser 。这些属性的值都是
布尔值,分别用于指明账户是否激活、是否为团队成员,以及是否拥有超级用户权限。
增加用户属性
除了 User 模型提供的属性之外,如果还需要其他用户相关的属性,要自己定义一个与 User 模型
关联的模型。对 Rango 应用而言,我们想为用户账户增加两个属性:
❏ 一个 URLField ,让 Rango 的用户设定自己的网站
❏ 一个 ImageField ,让 Rango 的用户设定自己的头像
为此,要在 Rango 应用的 models.py 文件中定义一个模型。我们把这个模型命名为 UserProfile 。
class UserProfile(models.Model):
# 这一行是必须的
# 建立与 User 模型之间的关系
user = models.OneToOneField(User)
# 想增加的属性
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
# 覆盖 __str__() 方法,返回有意义的字符串
# 如果使用 Python 2.7.x,还要定义 __unicode__ 方法
def __str__(self):
return self.user.username
注意,这个模型与 User 模型之间建立的一对一关系。因为引用了默认的 User 模型,所以要在
models.py 文件中导入它:
from django.contrib.auth.models import User
我们为 Rango 应用的用户账户增加了两个字段,还提供了 __str__() 方法,以便在需要
UserProfile 实例的字符串表示形式时返回有意义的值。注意,使用 Python 2 的话,还要定义
__unicode__() 方法,返回用户名的 Unicode 格式。
我们增加的 website 和 picture 字段都设定了 blank=True 。因此这两个字段都可以为空,不是必
须要提供值。
此外,注意 ImageField 字段的 upload_to 参数。这个参数的值与项目的 MEDIA_ROOT 设置(第 4
章)结合在一起,确定上传的头像存储在哪里。假如 MEDIA_ROOT 的值为
<workspace>/tango_with_django_project/media/ , upload_to 参数的值为 profile_images ,那么头
像将存储在 <workspace>/tango_with_django_project/media/profile_images/ 目录中。
★ 安装 PIL ★
Django 的 ImageField 字段要使用 Python Imaging Library(PIL)。如果你还未安装,执行
pip install pillow 命令,通过 pip 安装 PIL。如果未启用 JPEG 支持,也可以安装 PIL:
pip install pillow --global-option="build_ext" --global-option="--disable-jpeg" 。
若想查看(虚拟)环境中安装了哪些包,执行 pip list 命令。
如果想通过 Django 管理界面访问 UserProfile 模型数据,在 Rango 应用的 admin.py 模块中导入
UserProfile 模型:
from rango.models import UserProfile
然后注册模型:
admin.site.register(UserProfile)
★ 别忘了迁移 ★
定义新模型后必须更新数据库,别忘了!在终端或命令提示符中执行 python manage.py
makemigrations rango 命令,为新增的 UserProfile 模型创建迁移脚本。然后执行 python
manage.py migrate 命令,运行迁移,在底层数据库中创建相关的表。