新建accounts应用
python3 manage.py startapp accounts
创建models.py
# accounts/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class MyUser(AbstractUser):
"""自定义用户模型类"""
mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
# default为函数,如dict, list, tuple等
dbs = models.JSONField(verbose_name='我的数据库', default=list)
class Meta:
db_table = 'my_auth_user'
verbose_name = 'user'
verbose_name_plural = 'users'
配置settings.py
# proj/settings.py
# 安装应用
INSTALLED_APPS += ['accounts']
# 覆盖认证模型,注意不是accounts.models.MyUser
AUTH_USER_MODEL = 'accounts.MyUser'
使用MyUser
from accounts.models import MyUser
# 修改用户信息
u = MyUser.objects.get(username='admin')
u.mobile = '13812345678'
u.save()
# 新增用户
new_user = MyUser()
new_user.username = 'demo01'
new_user.set_password('123456')
配置admin
# accounts/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group
from .models import MyUser
from .forms import CustomUserCreationForm
ADDITIONAL_USER_FIELDS = (
(None, {'fields': ('email', 'mobile', 'dbs')}),
)
class CustomUserAdmin(UserAdmin):
model = MyUser
add_form = CustomUserCreationForm
list_display = ['username', 'email', 'mobile', 'dbs']
add_fieldsets = UserAdmin.add_fieldsets + ADDITIONAL_USER_FIELDS
admin.site.register(MyUser, CustomUserAdmin)
# admin.site.unregister(Group)
# accounts/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from accounts.models import MyUser
class CustomUserCreationForm(UserCreationForm):
# username = forms.CharField(label='用户名')
# password1 = forms.CharField(label='密码', widget=forms.PasswordInput)
# password2 = forms.CharField(label='确认密码', widget=forms.PasswordInput)
# email = forms.EmailField(label='邮箱地址', required=False)
# mobile = forms.CharField(label='手机号', required=False)
# dbs = forms.JSONField(label='数据库', required=False)
class Meta(UserCreationForm.Meta):
model = MyUser
fields = ('username', 'email', 'mobile', 'dbs')
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data["email"]
user.mobile = self.cleaned_data["mobile"]
user.dbs = self.cleaned_data["dbs"]
if commit:
user.save()
return user