Non-interactive superuser creation

Django News Issue 16 shared this:

hartwork/django-createsuperuserwithpassword: Django management command to create usable super users, programmatically

Django management command to programmatically create usable super users. This is great for local Docker development, but please skip for production.

Emphasis theirs.

The question I have is: What is the better way of doing non-interactive superuser account creation in production?

You could create a management command like hartwork did, or you could run things like:

echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', '', 'supersecretpass')" | python shell

But that may/may not handle custom User models, etc, but the basis of piping ORM code code into a shell is another way to go about this task.

But what is the best way as of Django 3.0 to do non-interactive superuser creation?

I appreciate your input!

I think they suggest to skip for production only because that’s not a good idea to create superusers in automatic uncontrollable way. I prefer doing this manually, since I can’t imagine a situation where you’d want to have more than let’s say five super users for a project. And it’s better to create those manually so you don’t leak their passwords anywhere.

Welcome to the forum @glasnt

On several projects I’ve used a post_migrate handler to add a super user if it doesn’t exist. Django uses this technique for content types. I wrote about it in #3 in this post:

I ended up chatting to a Django veteran about this, and worked out that I could use a migration against my initial project.

Only then I found Nicole’s post which shows mostly the same solution I worked out from scratch.

Hopefully this helps someone else!