Django已经给我们提供了一个用户模型,但是它的字段不多,在某些场景下无法满足我们的使用需求,所以我们还要重新定义个数据模型,来描述我们用户数据表。
原来的auth_user
表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| +--------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | password | varchar(128) | NO | | NULL | | | last_login | datetime | YES | | NULL | | | is_superuser | tinyint(1) | NO | | NULL | | | username | varchar(30) | NO | UNI | NULL | | | first_name | varchar(30) | NO | | NULL | | | last_name | varchar(30) | NO | | NULL | | | email | varchar(254) | NO | | NULL | | | is_staff | tinyint(1) | NO | | NULL | | | is_active | tinyint(1) | NO | | NULL | | | date_joined | datetime | NO | | NULL | | +--------------+--------------+------+-----+---------+----------------+
|
编辑我们的新建的用户app的models.py
先import AbstractUser,然后定义我们的类的时候,继承它就好了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser): nickname = models.CharField(verbose_name=u"用户名", max_length=50) birthday = models.DateField(verbose_name=u"生日", null=True, blank=True) gender = models.CharField(verbose_name=u"性别", choices=(("male", u'男'), ("female", u'女')), default="female", max_length=5) address = models.CharField(verbose_name=u"地址", max_length=100, default=u"") mobile = models.CharField(verbose_name=u"手机", max_length=11, null=True, blank=True) image = models.ImageField(verbose_name=u"头像", upload_to="images/%Y/%M", default=u"images/default.jpg")
class Meta: verbose_name = u"用户资料" verbose_name_plural = verbose_name
def __unicode__(self): return self.username
|
完事后在settings.py
注册我们的app,
再加上一条AUTH_USER_MODEL = "users.UserProfile"
指定我们新的用户模型
生成数据表
1 2
| makemigrations users migrate users
|
增加后新的表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| MySQL [opencourse]> desc users_userprofile; +--------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | password | varchar(128) | NO | | NULL | | | last_login | datetime | YES | | NULL | | | is_superuser | tinyint(1) | NO | | NULL | | | username | varchar(30) | NO | UNI | NULL | | | first_name | varchar(30) | NO | | NULL | | | last_name | varchar(30) | NO | | NULL | | | email | varchar(254) | NO | | NULL | | | is_staff | tinyint(1) | NO | | NULL | | | is_active | tinyint(1) | NO | | NULL | | | date_joined | datetime | NO | | NULL | | | nickname | varchar(50) | NO | | NULL | | | birthday | date | YES | | NULL | | | gender | varchar(5) | NO | | NULL | | | address | varchar(100) | NO | | NULL | | | mobile | varchar(11) | YES | | NULL | | | image | varchar(100) | NO | | NULL | | +--------------+--------------+------+-----+---------+----------------+
|
done.