When using continuous integration, it might be helpful to have a command which creates a Django superuser without any user interaction if none exist yet.

The default ./manage.py createsuperuser command doesn't allow you to do so, but you can easily create a custom management command which helps you doing this. Start with creating a file <app>/management/commands/createsuperuser_if_none_exists.py.

This will be used to add an extra management command to create the superuser if none exist allowing you to specify the username and password via the command-line arguments:

$ ./manage.py createsuperuser_if_none_exists --user=admin --password=change

The implementation is as follows:

<app>/management/commands/createsuperuser_if_none_exists.py

from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model

class Command(BaseCommand):
    """
    Create a superuser if none exist
    Example:
        manage.py createsuperuser_if_none_exists --user=admin --password=changeme
    """

    def add_arguments(self, parser):
        parser.add_argument("--user", required=True)
        parser.add_argument("--password", required=True)
        parser.add_argument("--email", default="admin@example.com")

    def handle(self, *args, **options):

        User = get_user_model()
        if User.objects.exists():
            return

        username = options["user"]
        password = options["password"]
        email = options["email"]

        User.objects.create_superuser(username=username, password=password, email=email)

        self.stdout.write(f'Local user "{username}" was created')

The logic is quite simple. The add_arguments allows us to easily define the required and options arguments for the command. We define 3 of them: --user, --password and an optional --email.

The handle function is called when you run the command. The first step is to check if there are any users. If there are users in the database already, we'll assume that the superuser is part of them and the command won't do anything.

If there are no users yet, we'll parse the arguments and then use User.objects.create_superuser to create the superuser.