Skip to content

Instantly share code, notes, and snippets.

Created March 30, 2018 16:03
Show Gist options
  • Save hartwork/f40bf2d311dfb41f29e9156e6057b2fa to your computer and use it in GitHub Desktop.
Save hartwork/f40bf2d311dfb41f29e9156e6057b2fa to your computer and use it in GitHub Desktop.
Django management command to script creation of superusers
# Django management command to create custom superusers
# Version 2018.03.18
# Core benefits over existing command `createsuperuser` are:
# - Scriptability
# - Ignorance of `settings.AUTH_PASSWORD_VALIDATORS`
# - Idempotency
# Store as `<app>/management/commands/` to activate.
# Originally written for Django 1.9.9.
# Copyright (C) 2018 Sebastian Pipping <>
# Licensed under CC0 1.0 Public Domain Dedication.
from import BaseCommand, CommandError
from django.contrib.auth.models import User
class Command(BaseCommand):
help = 'Used to create a _custom_ superuser.'
def add_arguments(self, parser):
credentials = parser.add_argument_group('credentials')
credentials.add_argument('--user', metavar='USER', dest='username',
help='user name (default: "%(default)s")')
credentials.add_argument('--password', metavar='PASSWORD',
help='password (default: "%(default)s")')
credentials.add_argument('--email', metavar='EMAIL',
help='e-mail address (default: "{}@{}")'
.format('<user>', _DEFAULT_EMAIL_DOMAIN))
def _report_success(self, message):
def _require_identical_configuration(self, user, password, email):
if not user.check_password(password):
raise CommandError('User "{}" exists but password differs.'
if != email:
raise CommandError('User "{}" exists but e-mail address differs.'
if not user.is_superuser:
raise CommandError('User "{}" exists but is not a superuser.'
def _create_new_superuser(self, username, password, email):
return User.objects.create_superuser(username=username,
def handle(self, *args, **options):
username = options['username']
password = options['password']
email = options['email']
if email is None:
email = '{}@{}'.format(username, _DEFAULT_EMAIL_DOMAIN)
user = User.objects.get(username=username)
except User.DoesNotExist:
user = self._create_new_superuser(username, password, email)
except Exception as e:
raise CommandError('Could not create user: {}'.format(e))
self._report_success('Superuser "{}" with e-mail address "{}"'
' created.'.format(username, email))
self._require_identical_configuration(user, password, email)
self._report_success('User "{}" with identical configuration '
'exists, nothing more to do.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment