manage_course_groups.py 2.04 KB
Newer Older
1 2 3 4 5 6
#!/usr/bin/python
#
# File:   manage_course_groups
#
# interactively list and edit membership in course staff and instructor groups

Calen Pennington committed
7
import re
8

9
from django.contrib.auth.models import Group, User
10
from django.core.management.base import BaseCommand
11

12 13 14 15

#-----------------------------------------------------------------------------
# get all staff groups

Calen Pennington committed
16

17 18 19 20 21 22
class Command(BaseCommand):
    help = "Manage course group membership, interactively."

    def handle(self, *args, **options):

        gset = Group.objects.all()
Calen Pennington committed
23

24
        print "Groups:"
Calen Pennington committed
25 26 27
        for cnt, g in zip(range(len(gset)), gset):
            print "%d. %s" % (cnt, g)

28
        gnum = int(raw_input('Choose group to manage (enter #): '))
Calen Pennington committed
29

30
        group = gset[gnum]
Calen Pennington committed
31

32 33
        #-----------------------------------------------------------------------------
        # users in group
Calen Pennington committed
34

35
        uall = User.objects.all()
Calen Pennington committed
36
        if uall.count() < 50:
37 38 39 40 41 42 43
            print "----"
            print "List of All Users: %s" % [str(x.username) for x in uall]
            print "----"
        else:
            print "----"
            print "There are %d users, which is too many to list" % uall.count()
            print "----"
Calen Pennington committed
44

45
        while True:
Calen Pennington committed
46

47
            print "Users in the group:"
Calen Pennington committed
48

49 50 51
            uset = group.user_set.all()
            for cnt, u in zip(range(len(uset)), uset):
                print "%d. %s" % (cnt, u)
Calen Pennington committed
52

53
            action = raw_input('Choose user to delete (enter #) or enter usernames (comma delim) to add: ')
Calen Pennington committed
54 55

            m = re.match('^[0-9]+$', action)
56 57 58 59 60
            if m:
                unum = int(action)
                u = uset[unum]
                print "Deleting user %s" % u
                u.groups.remove(group)
Calen Pennington committed
61

62 63 64 65 66 67 68 69 70
            else:
                for uname in action.split(','):
                    try:
                        user = User.objects.get(username=action)
                    except Exception as err:
                        print "Error %s" % err
                        continue
                    print "adding %s to group %s" % (user, group)
                    user.groups.add(group)