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'

 

posted @   守望人间  阅读(377)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· 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 让容器管理更轻松!
点击右上角即可分享
微信分享提示