How to create a Django superuser
Published on Aug. 22, 2023, 12:12 p.m.
Django includes a powerful admin interface that lets you interact with your site’s data more easily.Admin panel is one of the most useful Django features.
Let’s first see what a superuser is and how to create one .
Creating superuser in Django using the command line .
Before creating a superuser, ensure you have executed the migrate command since the admin interface is part of a django.contrib.admin module and superuser is using authentication mechanisms from the django.contrib.auth module.
$ python manage.py migrate
Now, to create a superuser.
$ python manage.py createsuperuser
Django will prompt you to enter the details such as username.
To create a Django superuser without prompt jumping out, you can define all the necessary data as environment variables.
$ export DJANGO_SUPERUSER_USERNAME=testuser
$ export DJANGO_SUPERUSER_PASSWORD=testpass
$ export DJANGO_SUPERUSER_EMAIL="[email protected]"
$ python manage.py createsuperuser --noinput
Create superuser in Django.
Another way of creating a desired superuser can be directly through code.
$ python manage.py shell
Then type the following snippet.
>>> from django.contrib.auth import get_user_model
>>> User = get_user_model()
>>> User.objects.create_superuser('testuser', '[email protected]', 'testpass')
In the above snippet, User model is imported from the pre-loaded authentication system.Then a superuser is created using the create_superuser() method.
You can also use it as a one-liner .
$ echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('testuser', '[email protected]', 'testpass')" | python manage.py shell