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"
    ),
]

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

Tips and Tricks Programming Django 4.x Django 3.2 Django 2.2 Django 1.11 Django 1.8