django兼容admin的自定义用户模型
参考https://docs.djangoproject.com/zh-hans/2.2/topics/auth/customizing/
1 from django.db import models 2 from django.contrib.auth.models import ( 3 BaseUserManager, AbstractBaseUser 4 ) 5 6 7 class MyUserManager(BaseUserManager): 8 def create_user(self, email, date_of_birth, password=None): 9 """ 10 Creates and saves a User with the given email, date of 11 birth and password. 12 """ 13 if not email: 14 raise ValueError('Users must have an email address') 15 16 user = self.model( 17 email=self.normalize_email(email), 18 date_of_birth=date_of_birth, 19 ) 20 21 user.set_password(password) 22 user.save(using=self._db) 23 return user 24 25 def create_superuser(self, email, date_of_birth, password): 26 """ 27 Creates and saves a superuser with the given email, date of 28 birth and password. 29 """ 30 user = self.create_user( 31 email, 32 password=password, 33 date_of_birth=date_of_birth, 34 ) 35 user.is_admin = True 36 user.save(using=self._db) 37 return user 38 39 40 class MyUser(AbstractBaseUser): 41 email = models.EmailField( 42 verbose_name='email address', 43 max_length=255, 44 unique=True, 45 ) 46 date_of_birth = models.DateField() 47 is_active = models.BooleanField(default=True) 48 is_admin = models.BooleanField(default=False) 49 50 objects = MyUserManager() 51 52 USERNAME_FIELD = 'email' 53 REQUIRED_FIELDS = ['date_of_birth'] 54 55 def __str__(self): 56 return self.email 57 58 def has_perm(self, perm, obj=None): 59 "Does the user have a specific permission?" 60 # Simplest possible answer: Yes, always 61 return True 62 63 def has_module_perms(self, app_label): 64 "Does the user have permissions to view the app `app_label`?" 65 # Simplest possible answer: Yes, always 66 return True 67 68 @property 69 def is_staff(self): 70 "Is the user a member of staff?" 71 # Simplest possible answer: All admins are staff 72 return self.is_admin
在setting中添加
1 AUTH_USER_MODEL = 'customauth.MyUser'
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!