Created
September 12, 2013 22:35
-
-
Save goliatone/6544739 to your computer and use it in GitHub Desktop.
Django create [default] user management command.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core.management.base import BaseCommand, CommandError | |
from optparse import make_option | |
from django.contrib.auth.models import User | |
class Command(BaseCommand): | |
help = 'Creates default user and password' | |
option_list = BaseCommand.option_list + ( | |
make_option( | |
"-u", | |
"--username", | |
dest="username", | |
default='admin', | |
help="specify user name", | |
metavar="USER" | |
), | |
) | |
option_list = option_list + ( | |
make_option( | |
"-p", | |
"--password", | |
dest="password", | |
default='admin', | |
help="user password, make it strong", | |
metavar="SLUG" | |
), | |
) | |
option_list = option_list + ( | |
make_option( | |
"-a", | |
"--admin", | |
dest="admin", | |
default=True, | |
help="user is super user", | |
metavar="ADMIN" | |
), | |
) | |
option_list = option_list + ( | |
make_option( | |
"-s", | |
"--staff", | |
dest="staff", | |
default=True, | |
help="user is super user", | |
metavar="ADMIN" | |
), | |
) | |
option_list = option_list + ( | |
make_option( | |
"-i", | |
"--initial", | |
dest="initial", | |
default=True, | |
help="only creates user if there are no previous users", | |
metavar="ADMIN" | |
), | |
) | |
def handle(self, *args, **options): | |
# if options['username'] is None: | |
# raise CommandError("Option `--user=...` must be specified.") | |
# if options['password'] is None: | |
# raise CommandError("Option `--password=...` must be specified.") | |
is_admin = options['admin'] | |
is_staff = options['staff'] | |
username = options['username'] | |
password = options['password'] | |
do_first = options['initial'] | |
if do_first and User.objects.count() > 0: | |
self.stdout.write("Found existing user.") | |
return | |
self.stdout.write("Creating user " + username) | |
admin = User.objects.create(username=username) | |
admin.set_password(password) | |
admin.is_superuser = is_admin | |
admin.is_staff = is_staff | |
admin.save() | |
self.stdout.write("User created.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment