A superuser in Django website is the admin of your website and has the ability to make pretty much any change on the website. Django comes with a built-in admin interface for every website. However, only superusers will be able to access and use it. There are two ways to create superuser in Django – through command prompt/terminal or programmatically. In this article, we will look at how to create superuser in Django.
How to Create Superuser in Django
Here are the steps to create superuser in Django.
1. Using Terminal or Command Prompt
In this case, first you need to navigate to the folder of your Django project, which contains manage.py file.
Then run the following command to create superuser named john
$ python manage.py createsuperuser
You will see a prompt to enter desired username.
Next, you will see a prompt to enter email address of user. You can leave it as blank, but it is useful to reset password in case you forget it.
Email address: firstname.lastname@example.org
Next, enter & re-enter the password for user.
Password: ****** Password(again): ******
If all goes well, you will the following message indicating that the superuser is created successfully.
Superuser created successfully.
Now you can start the Django server with following command.
$ python manage.py runserver
Open browser and visit http://127.0.0.1:8000/admin. You will see the following page with login scree. Enter the new username and password to proceed.
2. Create Superuser programmatically
You can also programmatically create Django superuser. Run either of the following commands from terminal or from within your script. Replace john, email@example.com and pass with your superuser’s username, email and password.
$ echo "from django.contrib.auth.models import User; User.objects.create_superuser('john', 'firstname.lastname@example.org', 'pass')" | python manage.py shell OR $ echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('john', 'email@example.com', 'pass')" | python manage.py shell
That’s it. In this article, we have learnt how to create superuser in Django.