django: create user profile for existing users automatically

前端 未结 3 1331
终归单人心
终归单人心 2021-01-03 18:47

I added a new UserProfile Model to my project today.

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

    def __unicode__(self         


        
相关标签:
3条回答
  • 2021-01-03 19:27

    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)
    
    0 讨论(0)
  • 2021-01-03 19:30

    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.

    0 讨论(0)
  • 2021-01-03 19:30

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

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题