Django: 指定したグループに権限を与える

1
2
3
4
from itertools import product
from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from django.apps import apps
 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
@main.command()
@click.argument("group_name")
@click.argument("model_path")
@click.argument("action_suffix", nargs=-1)  # view とか view_other とか
@click.pass_context
def group_add_perms(ctx, group_name, model_path, action_suffix):
    """指定したグループに権限を与える"""

    group = Group.objects.get(name=group_name)

    app_label, model_name = model_path.split(".")

    if app_label == "*":
        model_list = apps.get_models()
    else:
        model_list = list(
            filter(
                lambda i: model_name == "*" or i._meta.model_mame == model_name,
                apps.get_app_config(app_label).get_models(),
            )
        )

    actions = map(lambda i: i.split("_"), action_suffix)

    def _perm(item):
        model_class, actions = item
        content_type = ContentType.objects.get_for_model(model_class)
        codename = (
            f"{actions[0]}_{content_type.model}_{actions[1]}"
            if len(actions) > 1
            else f"{actions[0]}_{content_type.model}"
        )
        return Permission.objects.filter(content_type=content_type, codename=codename).first()

    perms = filter(lambda i: i is not None, map(_perm, product(model_list, actions)))
    group.permissions.add(*perms)