About Creating Groups with Permissions

You can create default groups and permissions programmatically as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.contrib.auth.models import Group, Permission

PERMISSIONS = [
    Permission.objects.get_by_natural_key(
        codename="add_post", app_label="blog", model="post"
    ),
    Permission.objects.get_by_natural_key(
        codename="add_page", app_label="cms", model="page"
    ),
]

group, _created = Group.objects.get_or_create(name="Creators")
group.permissions.add(*self.PERMISSIONS)

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