adduser.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
  2. from django.core.management.base import BaseCommand, CommandError
  3. from django.utils import timezone
  4. from optparse import make_option
  5. from misago.roles.models import Role
  6. from misago.users.models import UserManager
  7. class Command(BaseCommand):
  8. args = 'username email password'
  9. help = 'Creates new user account'
  10. option_list = BaseCommand.option_list + (
  11. make_option('--admin',
  12. action='store_true',
  13. dest='admin',
  14. default=False,
  15. help='Make a new user an administrator'),
  16. )
  17. def handle(self, *args, **options):
  18. if len(args) < 3:
  19. raise CommandError('adduser requires exactly three arguments: user name, e-mail addres and password')
  20. # Set user
  21. try:
  22. manager = UserManager()
  23. new_user = manager.create_user(args[0], args[1], args[2])
  24. except ValidationError as e:
  25. raise CommandError("New user cannot be created because of following errors:\n\n%s" % '\n'.join(e.messages))
  26. # Set admin role
  27. if options['admin']:
  28. new_user.roles.add(Role.objects.get(token='admin'))
  29. new_user.save(force_update=True)
  30. if options['admin']:
  31. self.stdout.write('Successfully created new administrator "%s"' % args[0])
  32. else:
  33. self.stdout.write('Successfully created new user "%s"' % args[0])
  34. self.stdout.write('\n\nNew user should use "%s" e-mail address and "%s" password to sign in.\n' % (args[1], args[2]))