After seeing this post, I tried to create my own group at project setup with this migration :
from django.db import migrations
from django.contrib.auth.models import Group, Permission
def create_group(apps, schema_editor):
group, created = Group.objects.get_or_create(name='thing_managers')
if created:
add_thing = Permission.objects.get(codename='add_thing')
group.permissions.add(add_thing)
group.save()
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20160720_1809'),
]
operations = [
migrations.RunPython(create_group),
]
But I got the following error :
django.contrib.auth.models.DoesNotExist: Permission matching query does not exist.
Here is my model :
class Thing(models.Model):
pass
Why can't I do that? How could I solve this?
I use django 1.9.
One solution is call the update_permissions command before try to append a permission
And as was commented don't import Group and Permission models use:
From this Django ticket, here's what worked for me in Django 3.0.4 and apparently will work in >=1.9:
Permissions are created in a
post_migrate
signal. They don't exist the first time migrations are run after a new model is added. It is probably easiest to run thepost_migrate
signal handler manually:create_permissions
checks for existing permissions, so this won't create any duplicates.