How to automate createsuperuser on django?

If you reference User directly, your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model. A more generic way to create the user would be:

echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', '[email protected]', 'password')" | python manage.py shell

ORIGINAL ANSWER

Here there is a simple version of the script to create a superuser:

echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', '[email protected]', 'pass')" | python manage.py shell

As of Django 3.0 you can use default createsuperuser --noinput command and set all required fields (including password) as environment variables DJANGO_SUPERUSER_PASSWORD, DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_EMAIL for example. --noinput flag is required.

This comes from the original docs: https://docs.djangoproject.com/en/3.0/ref/django-admin/#django-admin-createsuperuser

It is the most convenient way to add createsuperuser to scripts and pipelines.


I was searching for an answer to this myself. I decided to create a Django command which extends the base createsuperuser command (GitHub):

from django.contrib.auth.management.commands import createsuperuser
from django.core.management import CommandError


class Command(createsuperuser.Command):
    help = 'Crate a superuser, and allow password to be provided'

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--password', dest='password', default=None,
            help='Specifies the password for the superuser.',
        )

    def handle(self, *args, **options):
        password = options.get('password')
        username = options.get('username')
        database = options.get('database')

        if password and not username:
            raise CommandError("--username is required if specifying --password")

        super(Command, self).handle(*args, **options)

        if password:
            user = self.UserModel._default_manager.db_manager(database).get(username=username)
            user.set_password(password)
            user.save()

Example use:

./manage.py createsuperuser2 --username test1 --password 123321 --noinput --email '[email protected]'

This has the advantage of still supporting the default command use, while also allowing non-interactive use for specifying a password.