9

I try to write data migration code for custom user type but when I try to apply migration I get this:

TypeError: 'Permission' instance expected, got <Permission: my_app | Some Text | Can add some_model>

Looks weird to me. Isn't that a Permission instance? Here is my custom user model:

class Employee(AbstractUser):
    middle_name = models.CharField(max_length=60, null=True, blank=True)

And here is a piece of code in migration which raises this error (I guess so):

for user in User.objects.all():
    employee = orm.Employee.objects.create(
    id=user.id,
    username=user.username,
    first_name=user.first_name,
    last_name=user.last_name,
    password=user.password,
    email=user.email,

    is_active=user.is_active,
    is_superuser=user.is_superuser,
    last_login=user.last_login,
    date_joined=user.date_joined,
    )
    for perm in user.user_permissions.all():
        employee.user_permissions.add(perm)
Dmitrii Mikhailov
  • 5,053
  • 7
  • 43
  • 69

2 Answers2

0

When you create datamigration don't forget to use --freeze argument for all apps you somehow use in this migration, in my case it's auth:

python manage.py datamigration my_app --freeze auth

Then use orm['auth.User'].objects.all() instead of User.objects.all().

Dmitrii Mikhailov
  • 5,053
  • 7
  • 43
  • 69
  • This is quite old now, but is this still a valid way? I can't seem to find any documentation regarding the `freeze` argument or why you would use it. Can somebody elaborate or link to a better description? – bjrne Jun 15 '20 at 08:08
0

I am using user model as

from django.contrib.auth.models import AbstractUser

class MyProjectUser(AbstractUser):
...

and i create migration for add new permissions to some groups of users:

# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models


permissions_codenames = (
    'can_action_1',
    ...
    'can_action_10',
)


class Migration(DataMigration):

    def forwards(self, orm):
        "Write your forwards methods here."
        permissions = orm['auth.Permission'].objects.filter(codename__in=permissions_codenames)
        for user in orm.MyProjectUser.objects.filter(groups__name__in=('GroupName1', 'GroupName2')):
            user.user_permissions.add(*permissions)

    def backwards(self, orm):
        "Write your backwards methods here."
        permissions = orm['auth.Permission'].objects.filter(codename__in=permissions_codenames)
        for user in orm.MyProjectUser.objects.filter(groups__name__in=('GroupName1', 'GroupName2')):
            user.user_permissions.remove(*permissions)

    models = {
    ...
    }

    complete_apps = ['users']
    symmetrical = True

in complete_apps = ['users'] 'users' is app name, where located MyProjectUser class.

Shmele
  • 64
  • 6