python · 1月 16, 2023 0

How to create a Django superuser


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 migrate

Now, to create a superuser.

$ python 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.

$ python createsuperuser --noinput

Create superuser in Django.

Another way of creating a desired superuser can be directly through code.

$ python shell

Then type the following snippet.

>>> from django.contrib.auth import get_user_model
>>> User = get_user_model()
>>> User.objects.create_superuser('testuser', '', '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', '', 'testpass')" | python shell
%d 博主赞过: