App Engine Python SDK version 1.9.12
[gae.git] / python / lib / django-0.96 / django / contrib / auth / create_superuser.py
blob2e93c35b93e78bdc7f9bafd411c74b572806274d
1 """
2 Helper function for creating superusers in the authentication system.
4 If run from the command line, this module lets you create a superuser
5 interactively.
6 """
8 from django.core import validators
9 from django.contrib.auth.models import User
10 import getpass
11 import os
12 import sys
14 def createsuperuser(username=None, email=None, password=None):
15 """
16 Helper function for creating a superuser from the command line. All
17 arguments are optional and will be prompted-for if invalid or not given.
18 """
19 try:
20 import pwd
21 except ImportError:
22 default_username = ''
23 else:
24 # Determine the current system user's username, to use as a default.
25 default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower()
27 # Determine whether the default username is taken, so we don't display
28 # it as an option.
29 if default_username:
30 try:
31 User.objects.get(username=default_username)
32 except User.DoesNotExist:
33 pass
34 else:
35 default_username = ''
37 try:
38 while 1:
39 if not username:
40 input_msg = 'Username'
41 if default_username:
42 input_msg += ' (Leave blank to use %r)' % default_username
43 username = raw_input(input_msg + ': ')
44 if default_username and username == '':
45 username = default_username
46 if not username.isalnum():
47 sys.stderr.write("Error: That username is invalid. Use only letters, digits and underscores.\n")
48 username = None
49 continue
50 try:
51 User.objects.get(username=username)
52 except User.DoesNotExist:
53 break
54 else:
55 sys.stderr.write("Error: That username is already taken.\n")
56 username = None
57 while 1:
58 if not email:
59 email = raw_input('E-mail address: ')
60 try:
61 validators.isValidEmail(email, None)
62 except validators.ValidationError:
63 sys.stderr.write("Error: That e-mail address is invalid.\n")
64 email = None
65 else:
66 break
67 while 1:
68 if not password:
69 password = getpass.getpass()
70 password2 = getpass.getpass('Password (again): ')
71 if password != password2:
72 sys.stderr.write("Error: Your passwords didn't match.\n")
73 password = None
74 continue
75 if password.strip() == '':
76 sys.stderr.write("Error: Blank passwords aren't allowed.\n")
77 password = None
78 continue
79 break
80 except KeyboardInterrupt:
81 sys.stderr.write("\nOperation cancelled.\n")
82 sys.exit(1)
83 u = User.objects.create_user(username, email, password)
84 u.is_staff = True
85 u.is_active = True
86 u.is_superuser = True
87 u.save()
88 print "Superuser created successfully."
90 if __name__ == "__main__":
91 createsuperuser()