django: create user profile for existing users automatically

為{幸葍}努か 提交于 2020-01-22 17:11:07

问题


I added a new UserProfile Model to my project today.

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)

The above code will create a user profile for each new created user.

But how to create the user profile for each existing user automatically?

Thanks


回答1:


You can loop through the existing users, and call get_or_create():

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

You could put this in a data migration if you wish, or run the code in the shell.




回答2:


For existing users, it checks whether such an instance already exists, and creates one if it doesn't.

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

to connect signal use:

post_save.connect(post_save_create_or_update_profile)



回答3:


In response to your code I'll say to put a get_or_create also in a post_init listener for User.

If this "all fields null is ok" profile is just a fast example I'd put a middleware redirecting all users with no profile to the settings page asking them to fill additional data. ( probably you want to do this anyway, no one in the real world will add new data to their existing profiles if not forced or gamified into it :) )



来源:https://stackoverflow.com/questions/38640446/django-create-user-profile-for-existing-users-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!