How to create a Django superuser if it doesn't exist non-interactively?
<p>I want to automate creation of Django users via a Bash script. I found this snippet which almost suits my needs:   </p>

<pre><code>echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" |\
    python manage.py shell
</code></pre>

<p>How can I modify it so that it's a nop if the user already exists?</p>

<p>Using some <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/" rel="nofollow">QuerySet API</a> methods and a heredoc for readability:</p>

<pre><code>cat &lt;&lt;EOF | python manage.py shell
from django.contrib.auth.models import User
User.objects.filter(username="admin").exists() or \
    User.objects.create_superuser("admin", "admin@example.com", "pass")
EOF
</code></pre>

<p>Note that you should use the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.UserManager.create_superuser" rel="nofollow"><code>create_superuser()</code></a> helper function to create superusers instead of generic <code>User()</code> methods as it takes care of setting the password properly.    </p>

python django django-users