Dimitris Kougioumtzis Blog About technology

Django add permissions programmatically

Category Django

Posted on Nov. 7, 2017



django add permissions programmatically


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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])

About

My name is Dimitris Kougioumtzis and i work as a Web developer at Rapidbounce Company

Elsewhere