Django add permissions programmatically

Django -- Posted on Nov. 7, 2017

django add 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()

def set_permissions(apps=None, models=None, user=None, group=None):
    '''
    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']


    '''
    perms = []
    group_name = group if group else settings.PROJECT_GROUP
    group, created = Group.objects.get_or_create(name=group_name)
    if user:
        group.user_set.add(user)
    if apps:
        for app in 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 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])
                  
   
            

Related Posts