summaryrefslogtreecommitdiff
path: root/testapp/yaksh/management/commands/add_group.py
blob: 03ef1034c3a8dfcbe9b63725233418e00c3adc26 (plain)
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
'''
   This command adds moderator group with permissions to add, change and delete
   the objects in the exam app.
   We can modify this command to add more groups by providing arguments.
   Arguments like group-name, app-name can be passed.
'''

# django imports
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.db.utils import IntegrityError

class Command(BaseCommand):
    help = 'Adds the moderator group'

    def handle(self, *args, **options):
        app = 'yaksh'
        group = Group(name='moderator')
        try:
            group.save()
        except IntegrityError:
            raise CommandError("The group already exits")
        else:
            # Get the models for the given app
            content_types = ContentType.objects.filter(app_label=app)
            # Get list of permissions for the models
            permission_list = Permission.objects.filter(content_type=content_types)
            for permission in permission_list:
                group.permissions.add(permission)
                group.save()

        self.stdout.write('Moderator group added successfully')