[Django]-How is python manage.py createsuperuser useful?

5đź‘Ť

âś…

From the django-docs (emphasis mine):

This command is only available if Django’s authentication system (django.contrib.auth) is installed.

Creates a superuser account (a user who has all permissions). This is useful if you need to create an initial superuser account or if you need to programmatically generate superuser accounts for your site(s).

When run interactively, this command will prompt for a password for the new superuser account. When run non-interactively, no password will be set, and the superuser account will not be able to log in until a password has been manually set for it.

3đź‘Ť

python manage.py createsuperuser

in addition to mu’s answer, superuser is the one who can log into admin page and who can have permissions to add, edit, delete objects in thru admin page.

1đź‘Ť

Whenever you wipe your database or deploy to a server you often want to be able to setup up an “admin” account to be able to log into the /admin/ interface like this:

python manage.py createsuperuser -u admin -e admin@example.com --noinput
python manage.py changepassword admin

Unfortunately, usually you want your deployments to be automatic and as @mu pointed out you still must interactively set the password. However, you can just add the record to the database yourself if you want to automate the process:

echo "from django.contrib.auth.models import User" > createadmin.py
echo "User.objects.create_superuser('dan', 'dan@email.io', 'pass')" >> createadmin.py
python manage.py shell < createadmin.py

Of course don’t forget to set your password to something other than 'pass'.

1đź‘Ť

@hobs thanks for this awesome answer. it pointed me in the right direction with regards to finding an ultimate answer that worked for me. Below is my working config, the only difference is I modified the User import for newer versions of Django

from django.contrib.auth import get_user_model
User = get_user_model()
User.objects.create_superuser('adminuser', 'dev@email.io', 'password')

and the command I run is;

python3 manage.py shell < /opt/admin.py

I needed this for a Dockerfile config and below is how the line looks in Dockerfile line

RUN \
    python3 ./manage.py migrate && \
    python3 manage.py shell < adminuser.py

thanks again and hopefully someone else finds this useful

Leave a comment