About Using Permissions or ContentTypes in Data Migrations

Model permissions and content types are normally created after all migrations have completed by the post_migrate signal handlers. However, if you need to access them within a data migration, you must trigger their creation manually. You can do this by calling create_contenttypes() and create_permissions() before using them in the migration.

from django.db import migrations

def assign_article_permissions(apps, schema_editor):
    from django.contrib.auth.management import create_permissions
    from django.contrib.contenttypes.management import create_contenttypes

    app_config = apps.get_app_config("articles")
    Group = apps.get_model("auth", "Group")
    Permission = apps.get_model("auth", "Permission")

    create_contenttypes(app_config, apps=apps, verbosity=0)
    create_permissions(app_config, apps=apps, verbosity=0)

    admins_group, _ = Group.objects.get_or_create(name="Admins")

    permissions = Permission.objects.filter(content_type__app_label="articles")
    admins_group.permissions.set(permissions)
    admins_group.save()


class Migration(migrations.Migration):
    dependencies = [
        ("auth", "0012_alter_user_first_name_max_length"),
        ("contenttypes", "0002_remove_content_type_name"),
        ("articles", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(
            assign_article_permissions,
            migrations.RunPython.noop,
        ),
    ]

Tips and Tricks Programming Development Django 5.x Django 4.2 Django 3.2