(我已经通过了所有其他问题)我想自定义默认用户模型。这就是为什么我创建了一个新的django项目而没有做迁移的原因。我只是写了代码并保存了它www.example.com settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'authen',
]
AUTH_USER_MODEL = 'authen.CustomUser'
manager.py
from django.contrib.auth.base_user import BaseUserManager
class UserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError("Email is required")
email = self.normalize_email(email)
user = self.model(email=email,**extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser',True)
extra_fields.setdefault('is_active',True)
if extra_fields.get('is_staff') is not True:
raise ValueError("Super user must have is_staff true")
return self.create_user(email, password, **extra_fields)
models.py of authen app
from django.db import models
from django.contrib.auth.models import AbstractUser
from .manager import UserManager
class CustomUser(AbstractUser):
email = models.EmailField(unique=True)
phone = models.CharField(max_length=20)
nid = models.CharField(max_length=17,unique=True)
profile_picture = models.ImageField(upload_to='profile_pics', blank=True, null=True)
objects = UserManager()
REQUIRED_FIELDS=[]
USERNAME_FIELD = 'email'
class Meta:
app_label = 'CustomUser'
我没有做过任何迁移,我使用的是最新的Django和Python 3.1。我不得不为此创建几个项目。问我是否需要更多信息。
1条答案
按热度按时间cl25kdpy1#
Chatgpt是这4个小时调试中最差的。我只是在django.contrib.auth之前的install_apps中添加了authen应用程序
在我的模型里
而且成功了