Programmatically create a django group with permissions

Issue

In the Admin console, I can add a group and add a bunch of permissions that relate to my models, e.g.

api | project | Can add project
api | project | Can change project
api | project | Can delete project

How can I do this programmatically. I can’t find any information out there on how to do this.

I have:

from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType

from api.models import Project


new_group, created = Group.objects.get_or_create(name='new_group')
# Code to add permission to group ???
ct = ContentType.objects.get_for_model(Project)
# Now what - Say I want to add 'Can add project' permission to new_group?

UPDATE: Thanks for the answer you provided. I was able to use that to work out what I needed. In my case, I can do the following:

new_group, created = Group.objects.get_or_create(name='new_group')
proj_add_perm = Permission.objects.get(name='Can add project')
new_group.permissions.add(proj_add_perm)

Solution

Use below code

from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from api.models import Project
new_group, created = Group.objects.get_or_create(name='new_group')
# Code to add permission to group ???
ct = ContentType.objects.get_for_model(Project)

# Now what - Say I want to add 'Can add project' permission to new_group?
permission = Permission.objects.create(codename='can_add_project',
                                   name='Can add project',
                                   content_type=ct)
new_group.permissions.add(permission)

Answered By – anuragal

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published