set_staff.py 1.41 KB
Newer Older
1 2
from optparse import make_option

3 4 5 6 7 8
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
import re


class Command(BaseCommand):
9 10 11 12 13 14
    option_list = BaseCommand.option_list + (
        make_option('--unset',
                    action='store_true',
                    dest='unset',
                    default=False,
                    help='Set is_staff to False instead of True'),
15
    )
16 17

    args = '<user|email> [user|email ...]>'
18
    help = """
19
    This command will set is_staff to true for one or more users.
20 21 22 23
    Lookup by username or email address, assumes usernames
    do not look like email addresses.
    """

24
    def handle(self, *args, **options):
25
        if len(args) < 1:
26
            raise CommandError('Usage is set_staff {0}'.format(self.args))
27 28

        for user in args:
29
            if re.match(r'[^@]+@[^@]+\.[^@]+', user):
30 31 32
                try:
                    v = User.objects.get(email=user)
                except:
33
                    raise CommandError("User {0} does not exist".format(user))
34 35 36 37
            else:
                try:
                    v = User.objects.get(username=user)
                except:
38 39 40 41 42 43
                    raise CommandError("User {0} does not exist".format(user))

            if options['unset']:
                v.is_staff = False
            else:
                v.is_staff = True
44 45

            v.save()
46 47

        print 'Success!'