Flux
Flux

Reputation: 10930

How to automate create or update of superuser in Django?

From this question, I see that it's possible to update the creation of superusers in Django using:

echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', '[email protected]', 'password')" | python manage.py shell

This works for creating superusers, but not for updating them. Is there a way to automate the creation or update of superusers? Something similar to create_or_update.

Upvotes: 0

Views: 572

Answers (1)

Nalin Dobhal
Nalin Dobhal

Reputation: 2342

User.objects.create_superuser creates a user with is_staff=True and is_superuser=True. And update_or_create() first checks if any row exists with the given arguments.

So you can create a superuser with the command your added. i.e.

echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser(email='[email protected]', password='password')" | python manage.py shell

and update that row with the following:

echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.update_or_create(email='[email protected]', is_staff=True, is_superuser=True, defaults={'username': 'abcd'})" | python manage.py shell

It will create new user with there is no record found with the given data. You can further read about update_or_create().

Upvotes: 1

Related Questions