Management command createsuperuser
is used to create a superuser in a Django project, a user who can enter admin panel, manage other users and so on. Basically, it is the first user you want to create as soon as you deploy your Django project.
Creating a superuser with createsuperuser management command¶
This is a built-in Django command user to create a superuser account in a Django project's database.
The superuser account has administrative privileges and can access admin panel and manage project's data.
This management command is invoked by running the following in terminal:
python manage.py createsuperuser
If called without arguments it will give you prompts for all the data pieces it needs, like username, email and password.
Create superuser with a specific username¶
You can also supply an argument --username
:
python manage.py createsuperuser --username=admin
In this, the command will user username that you have provided as an argument and prompt you to enter email and password.
Create superuser with a specific email¶
Similarly, you can specify email for the superuser account as an argument
python manage.py createsuperuser --email=admin@example.com
This command will create a superuser account with the email "admin@example.com" and prompt you to enter username and password.
Bypassing prompts and providing all information¶
You can run command the command providing all information via arguments and --noinput
argument to completely avoid any prompts.
python manage.py createsuperuser --username=admin --email=admin@example.com --noinput
This command will create a superuser account with the provided username and email without any further prompts. The password will still need to be set manually in this case.
But, if you provide an environment variable containing the password, the user will be created with password set.
You can do it this way:
DJANGO_SUPERUSER_PASSWORD=somethingsupersecret123 python manage.py createsuperuser --username=admin --email=admin@example.com --noinput
Create superuser within a docker container¶
If you are running your project within docker compose you will need to prepend your command with docker compose command.
Let's assume the service with your Django project is called "web" then in order to run the createsuperuser
command will look like this:
docker compose run web python manage.py createsuperuser
Arguments, if needed, should go at the end of the command:
docker compose run web python manage.py createsuperuser --email=admin@example.com
Create a custom management command for unattended non-interactive superuser creation¶
Built-in command is great, but it doesn't check if the user is already created, thus consequent calls with the same inputs will result in error like this:
CommandError: Error: That username is already taken.
Automate creation of Django superuser¶
It is very convenient if you add a command to create superuser that will run non-interactively (not prompting user for input) on every deployment of your app during the release phase. This way it will ensure that user is created with a random password and user it will not spit out errors if users already exists because it would perform a check first.
Management commands are python scrips that reside within any Django application within your Django project that are included in the INSTALLED_APPS
list.
Within any of your apps you need to create a directory called management
within which a directory commands
and there will be your commands. Please note that management
and commands
must be python modules so that your commands can be imported. It means you need to also create empty files __init__.py
in both of them. Here is the structure of management
directory:
myapp
├── # other files
└── management
├── __init__.py
└── commands
├── __init__.py
└── makesuperuser.py
The management command I call makesuperuser
and here is the code:
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.utils.crypto import get_random_string
User = get_user_model()
class Command(BaseCommand):
def handle(self, *args, **options):
username = 'admin'
email = 'admin@example.com'
try:
u = None
if not User.objects.filter(username=username).exists() and not User.objects.filter(
is_superuser=True).exists():
print("admin user not found, creating one")
new_password = get_random_string(10)
u = User.objects.create_superuser(username, email, new_password)
print(f"===================================")
print(f"A superuser '{username}' was created with email '{email}' and password '{new_password}'")
print(f"===================================")
else:
print("admin user found. Skipping super user creation")
print(u)
except Exception as e:
print(f"There was an error: {e}")
You can run it with the following command:
python manage.py makesuperuser
In the output it will give you the username, email and password for the new user, and if executed again it will just print that the user already exists and not created.
Password will be generated randomly which is way better than hardcoding a password into your code which puts your projects at risk.