Source

django-registration-plus / registration / management / commands / createinvitations.py

Full commit
"""
A management command which gives an invitation to all registered users.

Calls ``RegistrationInvitation.objects.create_invitation()`` for all the users.

"""

from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User

from registration.models import RegistrationInvitation


class Command(BaseCommand):
    args = '[<username>] <number of invitations>'
    help = "Create invitations for users. If username is not specified all active users will get the specified number of invitations."
    
    def handle(self, *args, **options):
        args = list(args)
        l = len(args)
        v = int(options.get('verbosity', '0'))
        s = 0
        if l == 1:
            users = User.objects.filter(is_active=True)
        elif l == 2:
            username = args.pop(0)
            users = User.objects.filter(username=username, is_active=True)
        else:
            raise CommandError("You need to specify at least one argument.")
        
        try:
            n = args.pop(0)
            n = int(n)
        except:
            raise CommandError("Number of invitations (%s) needs to be an integer." % n)
        
        c = users.count()
        if not c:
            raise CommandError("No active users?" if l == 1 else "User with specified username (%s) not found or not active." % username)
        
        if v >= 2:
            print "Creating %d invitation%s for %d user%s:" % (n, 's' if n > 1 else '', c, 's' if c > 1 else '') if l == 1 else "Creating %d invitation%s for user %s:" % (n, 's' if n > 1 else '', username)
        
        for u in users:
            for i in range(0, n):
                RegistrationInvitation.objects.create_invitation(u)
                s += 1
            if v >= 2:
                open_invitations = RegistrationInvitation.objects.has_invitations(u)
                print "..user %s now has %d open invitation%s." % (u.username, open_invitations, 's' if open_invitations > 1 else '')
        
        if v >= 1:
            print "Created %d invitation%s for %d user%s" % (s, 's' if s > 1 else '', c, 's' if c > 1 else '') if l == 1 else "Created %d invitation%s for user %s" % (n, 's' if n > 1 else '', username)