Skip to content

Instantly share code, notes, and snippets.

@dimkoug
Created November 7, 2017 19:45
Show Gist options
  • Save dimkoug/80a44ad43d58a13c5d400e314b5d914c to your computer and use it in GitHub Desktop.
Save dimkoug/80a44ad43d58a13c5d400e314b5d914c to your computer and use it in GitHub Desktop.
django permissions programmatically
from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
User = get_user_model()
class SetPermisions:
'''
It is used to add permisions dynamically to a group.
Then user is assigned to this group
PROJECT_GROUP: is a string for example 'website_group'
user: is a user instance
apps: is a list of installed apps
for example apps = ['catalogue', 'products']
models: is a list of models
for example models = ['category', 'task']
'''
def __init__(self, apps=None, models=None, user=None, group=None):
self.apps = apps
self.models = models
self.user = user
self.group = group
def set_permissions(self):
perms = []
group_name = self.group if self.group else settings.PROJECT_GROUP
group, created = Group.objects.get_or_create(name=group_name)
if self.user:
group.user_set.add(self.user)
if self.apps:
for app in self.apps:
app_models = apps.get_app_config(app).get_models()
for model in app_models:
content_type = ContentType.objects.get_for_model(model)
permissions = Permission.objects.filter(
content_type=content_type)
perms.append(permissions)
if self.models:
for model in self.models:
content_type = ContentType.objects.get(model=model)
permissions = Permission.objects.filter(
content_type=content_type)
perms.append(permissions)
if group:
for p in perms:
group.permissions.add(*[perm for perm in p])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment