2016-05-14 23 views
1

我有坚持到一些不寻常的问题,即是需要根据不同的用户类型来创建配置文件 如。超不能有一个配置文件,而其他用户可以有轮廓后保存信号触发之前创建超级用户功能

我有扩展底座用户经理

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 

,然后用下面的信号I创建配置文件,我自己的用户模型

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

HM,不明白你的问题因为你已经在你的问题 – madzohan

+0

上回答了'if not instance.is_admin:'它会进入该块,即使它对超级用户 –

+0

当超级用户被创建时,stance.is_admin是错误的..虽然它不是真实的 –

回答

0

配置文件将为管理员创建的原因是因为您在create_superuser中使用了create_user。起初一个普通用户将被保存。这里的配置文件是为每个人创建的。两次这个用户将被修改为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 

OR

if instance.is_admin: UserProfile.objects.filter(user=instance).delete()

if not instance.is_admin后...但这种方式是不优雅

+0

为什么要删除配置文件....是不是有一个转折点,我可以避免为超级用户创建配置文件..重点是不创建首先 –

+0

TypeError:create_user()得到了一个意外的关键字参数'is_admin' –

+0

对不起,我会更新另一个。 – trantu