想使用django中的用戶認(rèn)證組件,但是其中用戶信息表的字段不夠用,可以自定義一張用戶表繼承自帶的用戶表實(shí)現(xiàn)想要的功能。
1.繼承用戶表并定義字段
from django.db import models
from django.contrib.auth.models import User, AbstractUser
class UserInfo(AbstractUser):
"""
用戶信息
"""
nid = models.AutoField(primary_key=True)
telephone = models.CharField(max_length=11, null=True, unique=True)
avatar = models.FileField(upload_to='avatars/', default="/avatars/default.png")
create_time = models.DateTimeField(verbose_name='創(chuàng)建時間', auto_now_add=True)
blog = models.OneToOneField(to='Blog', to_field='nid', null=True, on_delete=models.CASCADE)
def __str__(self):
return self.username
2.修改項(xiàng)目配置
此時不能直接使用python manage.py makemigrations命令做數(shù)據(jù)庫遷移,會報(bào)錯:
SystemCheckError: System check identified some issues:
ERRORS:
MyBlog.UserInfo.groups: (fields.E304) Reverse accessor for'UserInfo.groups' clashes with reverse accessor for 'User.groups'.
HINT: Add or change a related_name argument to the definition for 'UserInfo.groups' or 'User.groups'.
只需要修改項(xiàng)目中的settings.py遵岩,在其任意一行配置好自己剛剛寫好的用戶表路徑即可。
AUTH_USER_MODEL = "模塊名.UserInfo"
3.數(shù)據(jù)庫遷移
python manage.py makemigrations
python manage.py migrate