﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
35495	"Referencing default django.contrib packages permissions in data migrations, results in a ""race condition"""	braiam	nobody	"Using a data migration to create users and assign them permissions related to any of the base django.contrib applications on a clean environment results in Permission.DoesNotExist. I first used the forums to describe my findings, but this seems the best channel.

To reproduce:

*Make sure to not run manage.py migrate until the last step*

1. Create an empty project and an empty app inside (lets say polls)
2. Enable the contrib.auth app and the polls app
3. Create an empty migration file ""makemigration polls --empty""
4. Create an user and assign permissions for the User model in a data migration

{{{
def create_user(apps, schema_editor):
    User = apps.get_model(""auth"", ""User"")
    Permission = apps.get_model(""auth"", ""Permission"")
    ContentType = apps.get_model(""contenttypes"", ""contenttype"")

    user = User.objects.create_user(""new_user"")
   
    alias = schema_editor.connection.alias
    content_type_manager = ContentType.objects.db_manager(alias)
    user_type = content_type_manager.get_for_model(User, for_concrete_model=False)

    add_user_permission = Permission.objects.get(content_type=user_type, codename=""add_user"")

    user.user_permissions.add(add_user_permission)

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.RunPython(create_user),
    ]
}}}
5. Now migrate.

The result should be that every time that the migration exits an app migration scripts it should create the permissions for the models created by that app, instead, the permissions are created after all migrations are done.

I'm not sure if the permissions/contenttype should be created as tables are created, or if it should be delayed as long as possible until a data migration occurs. This would make these kind of scenarios not being able to deploy in a clean environment."	Bug	closed	Migrations	5.0	Normal	duplicate			Unreviewed	0	0	0	0	0	0
