我正在研究一个需要自定义用户模型的项目,因此我成功创建了一个自定义用户模型,但是在“管理”面板中编辑并保存用户后,出现错误,用户电子邮件被用户名替换。注册时,此问题不会出现,而只会在管理员中出现。
class UserAdminChangeForm(UserChangeForm):
def __init__(self, *args, **kargs):
super(UserAdminChangeForm, self).__init__(*args, **kargs)
class Meta:
model = User
fields = ('email', 'password', 'username', 'is_active', 'is_admin')
class UserManager(BaseUserManager):
def create_user(self, email, username, password=None, is_active=True,
is_admin= False, is_staff = False, is_profiled =False):
if not email:
raise ValueError("User must enter an email address.")
if not password:
raise ValueError("User must enter a password.")
if not username:
raise ValueError("User must enter a username.")
user_obj = self.model(email= self.normalize_email(email),username =
username )
user_obj.set_password(password)
user_obj.is_staff = is_staff
user_obj.is_admin = is_admin
user_obj.is_active = is_active
user_obj.profiled = is_profiled
user_obj.username = username
user_obj.save(using= self._db)
return user_obj
def create_staffuser(self, email, username, password=None):
user = self.create_user(email,username, password = password,
is_staff= True)
return user
def create_superuser(self, email, username, password=None, is_active =
True):
user = self.create_user(
email,
username,
password = password,
is_staff= True, is_admin = True, is_active = True
)
user.is_superuser = True
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique= True)
is_active = models.BooleanField(default= True)
is_staff = models.BooleanField(default= False)
is_admin = models.BooleanField(default= False)
profiled = models.BooleanField(default= False)
username = models.CharField(unique= True, blank=True, null =
True,max_length= 20)
#first_name = models.CharField(max_length= 20)
#updated = models.DateTimeField(auto_now = True)
timestamp = models.DateTimeField(auto_now_add = True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
答案 0 :(得分:0)
def save(self, *args, **kwargs):
user = super(UserAdminChangeForm, self).save(*args, **kwargs)
user.email = self.cleaned_data['email']
user.username = self.cleaned_data['username']
return user
必须覆盖save方法来修复它。似乎django由于某些未知原因而使两个字段不匹配。