2016-07-28 43 views
0

我今天加入了新的用户配置模式到我的项目。Django的:创建为现有用户的用户配置文件自动

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    ... 

    def __unicode__(self): 
     return u'Profile of user: %s' % (self.user.username) 

    class Meta: 
     managed = True 

def create_user_profile(sender, instance, created, **kwargs): 
    if created: 
     profile, created = UserProfile.objects.get_or_create(user=instance) 

post_save.connect(create_user_profile, sender=User) 

上述代码将为每个新创建的用户创建一个用户配置文件。

但如何为每一个现有的用户自动用户配置文件?

感谢

回答

3

您可以通过现有的用户环路,并调用get_or_create()

for user in User.objects.all(): 
    UserProfile.objects.get_or_create(user=user) 

,如果你愿意,你可以把这个在data migration,或在shell中运行代码。

+0

如何在数据迁移中做到这一点? – BAE

+1

我链接的文档解释了如何创建数据迁移。 – Alasdair

-2

在回答您的代码,我会说把一个get_or_create也处于post_init侦听用户。

如果这个“各个领域空是确定的”配置文件仅仅是一个快速的例子我把中间件重定向的所有用户,没有配置文件的设置页面,要求他们填写附加数据。 (可能是您无论如何要做到这一点,没有人在现实世界将新数据添加到现有的配置文件,如果不是被迫或游戏化到它:))

+0

我刚刚读了什么? – Nrzonline

0

对于现有的用户,它会检查这种情况是否已经存在,并创建一个,如果它不。

def post_save_create_or_update_profile(sender,**kwargs): 
    from user_profiles.utils import create_profile_for_new_user 
    if sender==User and kwargs['instance'].is_authenticate(): 
     profile=None 
     if not kwargs['created']: 
      try: 
       profile=kwargs['instance'].get_profile() 
       if len(sync_profile_field(kwargs['instance'],profile)): 
        profile.save() 
      execpt ObjectDoesNotExist: 
       pass 
     if not profile: 
      profile=created_profile_for_new_user(kwargs['instance']) 
    if not kwargs['created'] and sender==get_user_profile_model(): 
     kwargs['instance'].user.save() 

连接信号使用:

post_save.connect(post_save_create_or_update_profile) 
相关问题