Tuesday, August 25, 2015

Migrating old users into custom user model

Hello,

I have an existing project with migrations, datamigrations and I need a custom user model now, not just 1-1 profile so I created one.

However, when I switch the AUTH_USER_MODEL setting, I can't access the old auth.user model for my datamigration

def transfer_users(apps, schema_editor):
    OldUser = apps.get_model('auth', 'User')
    User = apps.get_model('users', 'User')
    for old_user in OldUser.objects.all():
        new_user = User.objects.create(
            date_joined=old_user.date_joined,
            email=old_user.email and old_user.email or '%s@example.com' % old_user.username,
            first_name=old_user.first_name,
            id=old_user.id,
            is_active=old_user.is_active,
            is_staff=old_user.is_staff,
            is_superuser=old_user.is_superuser,
            last_login=old_user.last_login,
            last_name=old_user.last_name,
            password=old_user.password)
        for perm in old_user.user_permissions.all():
            new_user.user_permissions.add(perm)
        for group in old_user.groups.all():
            new_user.groups.add(group)


class Migration(migrations.Migration):

    dependencies = [
        ('users', '0001_initial'),
        ('auth', '0006_require_contenttypes_0002'),
    ]

    operations = [
        migrations.RunPython(transfer_users)
    ]


Running this migration gives 
AttributeError: Manager isn't available; User has been swapped for 'users.User'
When trying to use OldUser.objects.all()

Is there another way to do this? Preferably in a datamigration not using a database shell


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7d85a040-ddc3-4c8e-8c8a-ed4d302baa87%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment