新建accounts应用

python3 manage.py startapp accounts

创建models.py

  1. # accounts/models.py
  2. from django.db import models
  3. from django.contrib.auth.models import AbstractUser
  4. class MyUser(AbstractUser):
  5. """自定义用户模型类"""
  6. mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
  7. # default为函数,如dict, list, tuple等
  8. dbs = models.JSONField(verbose_name='我的数据库', default=list)
  9. class Meta:
  10. db_table = 'my_auth_user'
  11. verbose_name = 'user'
  12. verbose_name_plural = 'users'

配置settings.py

  1. # proj/settings.py
  2. # 安装应用
  3. INSTALLED_APPS += ['accounts']
  4. # 覆盖认证模型,注意不是accounts.models.MyUser
  5. AUTH_USER_MODEL = 'accounts.MyUser'

使用MyUser

  1. from accounts.models import MyUser
  2. # 修改用户信息
  3. u = MyUser.objects.get(username='admin')
  4. u.mobile = '13812345678'
  5. u.save()
  6. # 新增用户
  7. new_user = MyUser()
  8. new_user.username = 'demo01'
  9. new_user.set_password('123456')

配置admin

  1. # accounts/admin.py
  2. from django.contrib import admin
  3. from django.contrib.auth.admin import UserAdmin
  4. from django.contrib.auth.models import Group
  5. from .models import MyUser
  6. from .forms import CustomUserCreationForm
  7. ADDITIONAL_USER_FIELDS = (
  8. (None, {'fields': ('email', 'mobile', 'dbs')}),
  9. )
  10. class CustomUserAdmin(UserAdmin):
  11. model = MyUser
  12. add_form = CustomUserCreationForm
  13. list_display = ['username', 'email', 'mobile', 'dbs']
  14. add_fieldsets = UserAdmin.add_fieldsets + ADDITIONAL_USER_FIELDS
  15. admin.site.register(MyUser, CustomUserAdmin)
  16. # admin.site.unregister(Group)
  1. # accounts/forms.py
  2. from django.contrib.auth.forms import UserCreationForm, UserChangeForm
  3. from django import forms
  4. from accounts.models import MyUser
  5. class CustomUserCreationForm(UserCreationForm):
  6. # username = forms.CharField(label='用户名')
  7. # password1 = forms.CharField(label='密码', widget=forms.PasswordInput)
  8. # password2 = forms.CharField(label='确认密码', widget=forms.PasswordInput)
  9. # email = forms.EmailField(label='邮箱地址', required=False)
  10. # mobile = forms.CharField(label='手机号', required=False)
  11. # dbs = forms.JSONField(label='数据库', required=False)
  12. class Meta(UserCreationForm.Meta):
  13. model = MyUser
  14. fields = ('username', 'email', 'mobile', 'dbs')
  15. def save(self, commit=True):
  16. user = super().save(commit=False)
  17. user.email = self.cleaned_data["email"]
  18. user.mobile = self.cleaned_data["mobile"]
  19. user.dbs = self.cleaned_data["dbs"]
  20. if commit:
  21. user.save()
  22. return user