2
votes

I'm migrating from django 1.8 to django 1.9.

I have a migration that adds a group user and then a permission django_comments.add_comment to that group. The migration that works with django 1.8 looks like this

from django.contrib.contenttypes.management import update_contenttypes
from django.contrib.auth.management import create_permissions


def create_perms(apps, schema_editor):
  update_contenttypes(apps.get_app_config('django_comments'))
  create_permissions(apps.get_app_config('django_comments'))

  Group = apps.get_model('auth', 'Group')
  group = Group(name='user')
  group.save()

  commentct = ContentType.objects.get_for_model(apps.get_model('django_comments', 'comment'))

  group.permissions.add([Permission.objects.get(codename='add_comment', content_type_id=commentct)])
  group.save()


class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
        ('django_comments', '0002_update_user_email_field_length')
    ]

    operations = [
        migrations.RunPython(create_perms, remove_perms)
    ]

When upgrading to django 1.9, this throws an error because the contenttype cannot be found. This is because when update_contenttypes call is not creating the necessary content_types. There is this line inside that function (django's source code reference)

def update_contenttypes(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs):
    if not app_config.models_module:
         return
    ...

This app_config.models_module is None in django 1.9, but is not None in django 1.8

If I replace that for this code

def update_contenttypes(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs):
    if not app_config.models_module:
         #return
         pass
    ...

Then all works ok.

The thing is I don't want to change django's core code. How can I make this work in django 1.9?

1

1 Answers

4
votes

Ok, thanks to some help in #django IRC (user knbk), I found an ugly workaround but at least it works!

Change this two lines

  update_contenttypes(apps.get_app_config('django_comments'))
  create_permissions(apps.get_app_config('django_comments'))

Write this instead

  app = apps.get_app_config('django_comments')
  app.models_module = app.models_module or True
  update_contenttypes(app)
  create_permissions(app)

Now it works just fine.