summaryrefslogtreecommitdiff
path: root/yaksh/management/commands/create_moderator.py
blob: c0f160a6c79f5b2d5e02d9a4e1587d5d96472640 (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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'''
   This command creates a moderator group and adds users to the moderator group
   with permissions to add, change and delete
   the objects in the exam app.
'''

# django imports
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User, Group, Permission

# local imports
from yaksh.models import create_group
from yaksh.views import _create_or_update_profile


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

    def add_arguments(self, parser):
        # Positional arguments
        parser.add_argument('usernames', nargs='*', type=str)

    def handle(self, *args, **options):
        app_label = 'yaksh'
        group_name = 'moderator'
        group = create_group(group_name, app_label)
        if group and isinstance(group, Group):
            self.stdout.write(self.style.SUCCESS(
                              'Moderator group added successfully'))

        if options['usernames']:
            for uname in options['usernames']:
                try:
                    user = User.objects.get(username=uname)
                except User.DoesNotExist:
                    raise CommandError(
                        'User "{0}" does not exist'.format(uname)
                    )
                if user in group.user_set.all():
                    self.stdout.write(
                        self.style.WARNING(
                            'User "{0}" is already'
                            ' a Moderator'.format(uname)
                        )
                    )
                else:
                    if not hasattr(user, 'profile'):
                        _create_or_update_profile(user,
                                                  {'is_email_verified': True}
                                                  )
                    user.profile.is_moderator = True
                    user.profile.save()
                    self.stdout.write(
                        self.style.SUCCESS(
                            'Successfully added User "{0}"'
                            ' to Moderator group'.format(uname)
                        )
                    )