错误:Django管理用户的变化形式的用户名替换电子邮件

问题描述 投票:0回答:1

我的工作需要自定义用户模型中的项目,所以我创建了一个自定义的用户模型成功,但在编辑和保存在管理控制台中的用户,我得到了用户的电子邮件将被替换为用户名的错误。在注册,这个问题不会显现,但只有在管理。

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()

admin page screenshot

django
1个回答
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最不匹配的一些未知的原因,这两个领域。


推荐问答