A simple Django management command to create a superuser non-interactively if one does not already exist.
This is useful for automating the setup of a Django application, for example, in a Docker container or a deployment script.
- Install the package using pip:
pip install django-ensuresuperuser- Add
django_ensuresuperuserto yourINSTALLED_APPSsetting in your Django project'ssettings.py:
INSTALLED_APPS = [
# ...
'django_ensuresuperuser',
]Assuming all variables are set, run the management command:
python manage.py ensuresuperuserThe command requires the following environment variables to be set:
DJANGO_SUPERUSER_PASSWORD: The password for the superuser.DJANGO_SUPERUSER_EMAIL(optional): The email for the superuser. Defaults toadmin@example.com.
The superuser will be created with the username admin.
If a user with the username admin already exists, the command will do nothing.
export DJANGO_SUPERUSER_PASSWORD="mysecretpassword"
export DJANGO_SUPERUSER_EMAIL="admin@mydomain.com"
python manage.py ensuresuperuser