BAE
BAE

Reputation: 8936

django: create user profile for existing users automatically

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

Upvotes: 0

Views: 2605

Answers (3)

Alasdair
Alasdair

Reputation: 308779

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.

Upvotes: 4

Alireza Aghamohammadi
Alireza Aghamohammadi

Reputation: 40

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)

Upvotes: 0

simone cittadini
simone cittadini

Reputation: 338

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

Upvotes: -2

Related Questions