我遇到了一些不寻常的问题,需要根据不同的用户类型创建配置文件 例如.super必须没有个人资料,而其他用户可以拥有个人资料
我有自己的用户模型,扩展了基本用户管理器
class MyUserManager(BaseUserManager):
def create_user(self, username=None, email=None, password=None):
"""
Creates and saves a User with the given username, email and password.
"""
if not username:
raise ValueError('Must include username')
if not email:
raise ValueError('Users must have an email address')
user = self.model(
username = username,
email = self.normalize_email(email),
gender='MALE',
)
user.set_password(password)
user.save(using=self._db)
print user
return user
def create_superuser(self, username, email, password):
"""
Creates and saves a superuser with the given username, email and password.
"""
user = self.create_user(
username=username,
email=email,
password=password,
)
user.is_admin = True
print user, user.is_admin
user.save(using=self._db)
return user
然后使用以下信号我创建个人资料
def new_user_receiver(sender, instance, created, *args, **kwargs):
if not instance.is_admin:
print instance , instance.is_admin , not instance.is_admin
new_profile, is_created = UserProfile.objects.get_or_create(user=instance)
else:
pass
post_save.connect(new_user_receiver, sender=MyUser)
我现在面临的问题是,一旦创建用户并且为超级用户创建了配置文件,上述信号就会被触发
有没有办法可以避免为超级用户创建配置文件?
谢谢。
答案 0 :(得分:0)
为管理员创建个人资料的原因是您在create_user
中使用create_superuser
。首先,将保存普通用户。这里为每个人创建了配置文件。两次此用户将被修改为admin。您应该在create_superuser
函数中调用它:
def create_user(self, username=None, email=None, password=None, is_admin=False):
"""
Creates and saves a User with the given username, email and password.
"""
if not username:
raise ValueError('Must include username')
if not email:
raise ValueError('Users must have an email address')
user = self.model(
username = username,
email = self.normalize_email(email),
gender='MALE',
is_admin = is_admin,
)
user.set_password(password)
user.save(using=self._db)
print user
return user
def create_superuser(self, username, email, password):
"""
Creates and saves a superuser with the given username, email and password.
"""
user = self.create_user(
username=username,
email=email,
password=password,
is_admin = True,
)
return user
或强>
if instance.is_admin:
UserProfile.objects.filter(user=instance).delete()
在if not instance.is_admin
之后......但这种方式并不优雅