Create user profiles in Django if they does not exist

#StandWithUkraine
Today, 25th June 2022, Ukraine is still bravely fighting for democratic values, human rights and peace in whole world. Russians ruthlessly kill all civilians in Ukraine including childs and destroy their cities. We are uniting against Putin’s invasion and violence, in support of the people in Ukraine. You can help by donating to Ukrainian's army.

If you store additional user information in a custom profile model, possibly you have post_save hook to create them during signup:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # your fields

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

But if you already have users in your database without profiles, possibly you need also create them. This will allow omitting redundant checks e.g. if getattr(request.user.profile).

To do this we can create migration like described in datamigration hint, with the next action:

def create_profiles(apps, schema_editor):
    User = apps.get_model(app_label='auth', model_name='User')
    Profile = apps.get_model("main", "Profile")
    for u in User.objects.all():
        if not hasattr(u, 'profile'):
            Profile.objects.create(user=u)
            u.save()

class Migration(migrations.Migration):
    dependencies = [
        ('main', '0018_auto_20170408_1407'),
    ]
    operations = [
         migrations.RunPython(create_profiles),
    ]
#django
0
Ivan Borshchov profile picture
Apr 08, 2017
by Ivan Borshchov
Did it help you?
Yes !
No

Best related