#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:

<app>/management/commands/createsuperuser_if_none_exists.py

 1from django.core.management.base import BaseCommand
 2from django.contrib.auth import get_user_model
 3
 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    """
10
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")
15
16    def handle(self, *args, **options):
17
18        User = get_user_model()
19        if User.objects.exists():
20            return
21
22        username = options["user"]
23        password = options["password"]
24        email = options["email"]
25
26        User.objects.create_superuser(username=username, password=password, email=email)
27
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.