自定义user模型有很多方法,继承AbstractUser只是我认为比较好的一种方法。
1、首先自定义一个user模型UserProfile,可以扩展自己需要的属性
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UserProfile(AbstractUser):
'''扩展Django自带的User模型'''
user_name = models.CharField(max_length=200)
user_weburl = models.CharField(max_length=200, default = "www.loveu888.com")
2、在settings.py文件末尾添加一下内容,用自己定义的UserProfile模型代替系统的user模型
#自定义user
AUTH_USER_MODEL = 'admin_web.UserProfile' //admin_web为自己的app名
3、在自己app的admin.py文件里面注册自己的UserProfile模型
from admin_web.models import UserProfile
# Register your models here.
admin.site.register(UserProfile)
但是这样做有个问题是什么呢,当你在后台管理系统,用户模型中添加了一个用户后,发现密码是明文的,这样就导致你无法登录你新创建的用户,怎么解决呢?往下看。
那么在app的admin.py文件里就要这样写了
from admin_web.models import UserProfile
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy
# Register your models here.
class UserProfileAdmin(UserAdmin):
list_display = ('username','last_login','is_superuser','is_staff','is_active','date_joined')
fieldsets = (
(None,{'fields':('username','password','first_name','last_name','email','user_phone')}),
# (gettext_lazy('User Information'),{'fields':('user','birthday','gender','mobile')}),
# (gettext_lazy('Permissions'), {'fields': ('is_superuser','is_staff','is_active',
# 'groups', 'user_permissions')}),
# (gettext_lazy('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
admin.site.register(UserProfile, UserProfileAdmin)
定义一个继承系统UserAdmin的UserProfileAdmin类,在这个类里面就可以按照我们的需求自己配置用户模型中的字段了
5、最后迁移数据库
python manage.py makemigrations
python manage.py migrate
网友评论