I have a data migration that updates some permissions. I know there are some known issues with permissions in migrations and i was able to avoid some trouble by creating the permissions in the migration it self (rather then using the tuple shortcut in the model).
The migration :
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
def create_feature_groups(apps, schema_editor):
app = models.get_app('myauth')
Group = apps.get_model("auth", "Group")
pro = Group.objects.create(name='pro')
Permission = apps.get_model("auth", "Permission")
ContentType = apps.get_model("contenttypes", "ContentType")
invitation_contenttype = ContentType.objects.get(name='Invitation')
send_invitation = Permission.objects.create(
codename='send_invitation',
name='Can send Invitation',
content_type=invitation_contenttype)
pro.permissions.add(receive_invitation)
class Migration(migrations.Migration):
dependencies = [
('myauth', '0002_initial_data'),
]
operations = [
migrations.RunPython(create_feature_groups),
]
After some trial and error i was able to make this work using manage.py migrate
but i'm getting errors in the test manage.py test
.
__fake__.DoesNotExist: ContentType matching query does not exist.
Debugging a bit discovered that there are no ContentType
at this point in the migration when run in test (not sure why). Following the advice in this post i tried updating the content types manually in the migration it self. Added :
from django.contrib.contenttypes.management import update_contenttypes
update_contenttypes(app, models.get_models())
before fetching the content type for the Invitation
model. Got the following error
File "C:\Python27\lib\site-packages\django-1.7-py2.7.egg\django\contrib\contenttypes\management.py", line 14, in update_contenttypes
if not app_config.models_module:
AttributeError: 'module' object has no attribute 'models_module'
There must be some way to create/update permissions in data migrations in a testable way.
Thanks.
EDIT
Finally made it work by adding
from django.contrib.contenttypes.management import update_all_contenttypes
update_all_contenttypes()
oddly enough this one was not sufficient
update_contenttypes(apps.app_configs['contenttypes'])
I would love to know why all of this is necessary
The answer is:
apps.get_model('contenttypes', 'ContentType')
:) Needed it myself today.