#django #python

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:

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

The implementation is as follows:


 1from django.core.management.base import BaseCommand
 2from django.contrib.auth import get_user_model
 4class Command(BaseCommand):
 5    """
 6    Create a superuser if none exist
 7    Example:
 8        manage.py createsuperuser_if_none_exists --user=admin --password=changeme
 9    """
11    def add_arguments(self, parser):
12        parser.add_argument("--user", required=True)
13        parser.add_argument("--password", required=True)
14        parser.add_argument("--email", default="admin@example.com")
16    def handle(self, *args, **options):
18        User = get_user_model()
19        if User.objects.exists():
20            return
22        username = options["user"]
23        password = options["password"]
24        email = options["email"]
26        User.objects.create_superuser(username=username, password=password, email=email)
28        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.