Abdelghani
Abdelghani

Reputation: 93

Django - create profile for all existing users

i'm using Django 3 , this is my userprofile model

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from django.db.models.signals import post_save
from django.utils.text import slugify 
from django.db.models import signals

# Create your models here.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=1000,blank=True)
    created_at = models.DateTimeField(default=datetime.now())
    slug = models.SlugField(blank=True)
    img = models.ImageField(upload_to='userimg/',default='userimg/avatar.png')

    def __str__(self):
        return "%s" % self.user

    def save(self, *args, **kwargs):
        self.slug = slugify(self.user)
        super(Profile, self).save(*args, **kwargs)

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.get(user=instance)

post_save.connect(create_user_profile, sender=User)

def delete_user(sender, instance=None, **kwargs):
    try:
        instance.user
    except User.DoesNotExist:
        pass
    else:
        instance.user.delete()

signals.post_delete.connect(delete_user, sender=Profile)

the problem is that the function create_user_profile create profiles only for the new users but doesn't create for the old users , so how can i fix that ?

Upvotes: 1

Views: 1674

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

You can make a data migration. You create one with:

python3 manage.py makemigrations --empty app_name

where you replace app_name with the name of the app that stores the Profile model. In the migration, you can then make Profile models:

from django.db import migrations
from django.conf import settings

def make_profiles(apps, schema_editor):
    User = apps.get_model(settings.AUTH_USER_MODEL)
    Profile = apps.get_model('app_name', 'Profile')
    profiles = [Profile(user=user) for user in User.objects.filter(profile=None)]
    Profile.objects.bulk_create(profiles)

class Migration(migrations.Migration):

    dependencies = [
        ('app_name', '1234_some_migration'),
    ]

    operations = [
        migrations.RunPython(make_profiles),
    ]

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Upvotes: 2

Related Questions