228

I want to auto run manage.py createsuperuser on django but it seams that there is no way of setting a default password.

How can I get this? It has to be independent on the django database.

Iulius Curt
  • 4,984
  • 4
  • 31
  • 55
bogdan
  • 9,056
  • 10
  • 37
  • 42
  • 1
    have you looked into just saving your created superuser a fixture and loading it using manage.py? – turbotux Feb 27 '17 at 23:01
  • 1
    @turbotux Hendrik F answer takes a similar approach to what you suggest, with the added ability to read the values (login, password...) from env vars (or filesystem, ...). I would highly suggest going this direction instead of the ad-hoc python scripts, which have problems when you restart the application. – Ad N Jul 24 '19 at 09:28

25 Answers25

204

As of Django 3.0 you can use default createsuperuser --noinput command and set all required fields (including password) as environment variables DJANGO_SUPERUSER_PASSWORD, DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_EMAIL for example. --noinput flag is required.

This comes from the original docs: https://docs.djangoproject.com/en/3.0/ref/django-admin/#django-admin-createsuperuser

It is the most convenient way to add createsuperuser to scripts and pipelines.

Alexey Trofimov
  • 4,287
  • 1
  • 18
  • 27
  • 8
    Thank you! this was very helpful, it's perfect to be used with `docker-compose` this answer should be on the top – Bilal Sep 09 '20 at 22:25
  • 3
    this is very important for the docker setup. thanks a ton. – sid8491 Oct 28 '20 at 11:31
  • 1
    In the context of Dockerizing Django, this is awesome! Exactly what I was wondering if existed. – Jarad Apr 22 '21 at 19:58
  • 2
    How do you use this with docker compose? – Phil O Aug 05 '21 at 03:19
  • 2
    @PhilO create new ".env" file with mentioned environment variables . you can attach the vars into your django container with --env-file https://docs.docker.com/compose/environment-variables/ inside the container run " python manage.py createsuperuser --no-input" – Ayman Ferki Aug 31 '21 at 00:31
  • The advantage of this solution is that you can keep environment variables out of public code, which is necessary for security. – setnoset Sep 11 '22 at 09:23
  • Cool and modern solution! Thanks. Btw, does anybody know if it's possible to crypt the django superuser password in the .env file? – swiss_knight Nov 12 '22 at 12:09
  • It does not seem to work with docker-compose, if you want to run an extra command. Even the simplest example seems not to be working ` python manage.py createsuperuser --noinput --username=admin --email=admin@example.com --password=password ` – Michael Paris Feb 06 '23 at 00:10
  • 1
    @AymanFerki For passing sensitive information, you should rather use secrets: https://docs.docker.com/compose/use-secrets/ – tschomacker May 24 '23 at 10:06
196

If you reference User directly, your code will not work in projects where the AUTH_USER_MODEL setting has been changed to a different user model. A more generic way to create the user would be:

echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', 'admin@myproject.com', 'password')" | python manage.py shell

ORIGINAL ANSWER

Here there is a simple version of the script to create a superuser:

echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" | python manage.py shell
Tk421
  • 6,196
  • 6
  • 38
  • 47
  • 2
    super useful when trying to create superuser in heroku and your network blocks port 5000 – Vic Jun 09 '16 at 05:40
  • 6
    I would delete the existing superuser, so this is valid for every build: ```echo "from django.contrib.auth.models import User; User.objects.filter(email='admin@example.com').delete(); User.objects.create_superuser('admin@example.com', 'admin', 'nimda')" | python manage.py shell ``` – Montaro Nov 01 '16 at 15:04
  • 20
    Personally I don't think deleting the user on each build is a good idea. You risk unintentionally deleting any associated records via a cascade delete. A safer option is to simply bail-out if the user already exists (or update the existing User record). – Will Jan 07 '17 at 01:15
  • 6
    At least on Django 1.11. the order of the arguments is ('username', 'email', 'pass'), not ('email', 'username', 'pass'). See: https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.UserManager – Niko Föhr May 14 '17 at 12:29
  • 5
    `from django.contrib.auth.models import User` no longer works. Use this: `from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', 'admin@myproject.com', 'my secure password')` – dcalde Jun 10 '18 at 13:58
  • @dcalde thanks for your comment, using [get_user_model](https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#django.contrib.auth.get_user_model) covers more use cases. – Tk421 Jun 11 '18 at 01:26
  • Had to do it without quotes, windows 10 x64 python 3.6 with virtualenv `echo from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', 'admin@myproject.com', 'password') | python manage.py shell` – Abdul Hfuda Nov 12 '18 at 18:45
  • I feel a bit bad down-voting this, because I'm sure it was the right answer when it was written. But the question specifically asks about `./manage.py createsuperuser` and it's now possible to do what the OP wants with that tool, as another answer shows. – Ben Butler-Cole May 11 '21 at 15:06
  • I would strongly suggest to use the [Data Migration approach](https://stackoverflow.com/a/53555252/1636885) as suggested by [Hendrik F](https://stackoverflow.com/a/53555252/1636885) later: "it naturally addresses the biggest problem of the accepted answer (a migration is applied only once on a deployment, so the user is only created once -> otherwise, you will get the "**User already exists**" error)". – TruthTeller May 20 '22 at 07:18
67

I use './manage.py shell -c':

./manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'adminpass')"

This doesn't uses an extra echo, this has the benefit that you can pass it to a docker container for execution. Without the need to use sh -c "..." which gets you into quote escaping hell.

And remember that first comes username, then the email.

If you have a custom user model you need to import that and not auth.models.User

Marcel Wilson
  • 3,842
  • 1
  • 26
  • 55
yvess
  • 1,992
  • 19
  • 17
  • Doesn't appear to work for me, I'm seeing: `AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User'` – Brodan Nov 26 '18 at 16:39
  • 2
    when you have a custom user model like `users.User` you need to import from that and not from `auth.User` – yvess Feb 26 '19 at 15:31
66

I was searching for an answer to this myself. I decided to create a Django command which extends the base createsuperuser command (GitHub):

from django.contrib.auth.management.commands import createsuperuser
from django.core.management import CommandError


class Command(createsuperuser.Command):
    help = 'Crate a superuser, and allow password to be provided'

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--password', dest='password', default=None,
            help='Specifies the password for the superuser.',
        )

    def handle(self, *args, **options):
        password = options.get('password')
        username = options.get('username')
        database = options.get('database')

        if password and not username:
            raise CommandError("--username is required if specifying --password")

        super(Command, self).handle(*args, **options)

        if password:
            user = self.UserModel._default_manager.db_manager(database).get(username=username)
            user.set_password(password)
            user.save()

Example use:

./manage.py createsuperuser2 --username test1 --password 123321 --noinput --email 'blank@email.com'

This has the advantage of still supporting the default command use, while also allowing non-interactive use for specifying a password.

Adam Charnock
  • 1,596
  • 1
  • 13
  • 17
  • I wish the default `createsuperuser` had this `--password` field too – Shadi Dec 14 '17 at 15:14
  • 2
    You could add an example usage: `./manage.py createsuperuser2 --username test1 --password 123321 --noinput --email 'blank@email.com'` – Shadi Dec 14 '17 at 15:18
  • 2
    how is `createsuperuser2` mapped to this class, function – Srinath Ganesh Jun 26 '18 at 03:19
  • 3
    @SrinathGanesh have a look at https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/ You need to name the python file `createsuperuser2.py` and place it into the defined directory structure from the link above. – ElectRocnic Sep 23 '18 at 12:19
  • It's not safe to pass a password through command line. Another user could see the password in process list. – mymedia May 21 '21 at 14:27
  • In order to command createsuperuser2, 1. make "management" folder under random application folder 2. make "commands" folder under the management folder 3. make "createsuperuser2.py" and use the extension code above. Refer to the django documentation below for 1) directory structure for custom commands, 2) how to make custom command: https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/ – Young-jin Ahn Jul 19 '21 at 09:55
60

I would suggest running a Data Migration, so when migrations are applied to the project, a superuser is created as part of the migrations. The username and password can be setup as environment variables. This is also useful when running an app in a container (see this thread as an example)

Your data migration would then look like this:

import os
from django.db import migrations

class Migration(migrations.Migration):
    dependencies = [
        ('<your_app>', '<previous_migration>'),
    ] # can also be emtpy if it's your first migration

    def generate_superuser(apps, schema_editor):
        from django.contrib.auth.models import User

        DJANGO_SU_NAME = os.environ.get('DJANGO_SU_NAME')
        DJANGO_SU_EMAIL = os.environ.get('DJANGO_SU_EMAIL')
        DJANGO_SU_PASSWORD = os.environ.get('DJANGO_SU_PASSWORD')

        superuser = User.objects.create_superuser(
            username=DJANGO_SU_NAME,
            email=DJANGO_SU_EMAIL,
            password=DJANGO_SU_PASSWORD)

        superuser.save()

    operations = [
        migrations.RunPython(generate_superuser),
    ]

Hope that helps!

EDIT: Some might raise the question how to set these environment variables and make Django aware of them. There are a lot of ways and it's been answered in other SO posts, but just as a quick pointer, creating a .env file is a good idea. You could then use the python-dotenv package, but if you have setup a virtual environment with pipenv, it will automatically set the envvars in your .env file. Likewise, running your app via docker-compose can read in your .env file.

John Vandenberg
  • 474
  • 6
  • 16
Hendrik F
  • 3,690
  • 3
  • 21
  • 24
  • 5
    **TIP: Please consider this approach**. This is a high quality answer: it naturally leverages built-in functionalities of Django to answer the question instead of echoing ad-hoc python scripts, plus it naturally addresses the biggest problem of the accepted answer (a migration is applied only once on a deployment, so the user is only created once). It works beautifully in a container context. – Ad N Jul 24 '19 at 09:23
  • This seems a great answer. I still don't know where in the project does this piece of code fit? – Pablo Ruiz Ruiz Oct 27 '19 at 13:23
  • 2
    It should be in your migrations folder, e.g `root/⁨mysite⁩/myapp⁩/⁨migrations⁩` - if your read the docs, it explains how you can create an empty migration and modify that `python manage.py makemigrations --empty yourappname` – Hendrik F Oct 28 '19 at 07:38
  • 1
    Why do you need the DJANGO_DB_NAME? it is never used. – thoroc Jun 13 '20 at 19:22
  • You should mention to add the following to load the .env vars to the `settings.py` file: `python # loading .env from dotenv import load_dotenv from pathlib import Path env_path = Path('.', '.env') load_dotenv(dotenv_path=env_path) ` – thoroc Jun 13 '20 at 19:35
  • I wanted to make a User if non exist. So I boiled creting superuser down to `superuser = User.objects.create_superuser(username="Admin", password="1234")` no .env required. Answer to different question tho. – Brambor Aug 31 '20 at 21:51
  • 1
    This fails when using a custom user model. After you add this migration you will no longer be able to add columns when using a fresh db. – agconti Sep 07 '21 at 20:18
  • In order to get this to work I had to pass `last_login=django.utils.timezone.now()` to create_superuser. – Dedalus Nov 25 '21 at 16:56
  • 1
    A high quality answer but this fails on a custom user model, please consider using `django.contrib.auth.get_user_model` instead of importing this model – Ahmed I. Elsayed Oct 26 '22 at 00:57
36
DJANGO_SUPERUSER_USERNAME=testuser \
DJANGO_SUPERUSER_PASSWORD=testpass \
DJANGO_SUPERUSER_EMAIL="admin@admin.com" \
python manage.py createsuperuser --noinput

Documentation for the createuser command

titusfx
  • 1,896
  • 27
  • 36
Rafal Enden
  • 3,028
  • 1
  • 21
  • 16
  • 10
    This is the easiest solution. But you can overwrite `noinput` flag with other params: `DJANGO_SUPERUSER_PASSWORD=testpass python manage.py createsuperuser --username testuser --email admin@email.com --noinput` – dannydedog Jun 23 '20 at 10:51
  • 4
    This method works in *`Django 3.0`* and later not in *`Django 2.2`* – Benyamin Jafari Dec 27 '20 at 08:36
  • 3
    It doesn't on Django 4.0 you need to pass email. Otherwise you will receive the following error: `CommandError: You must use --email with --noinput.` – titusfx Feb 04 '22 at 09:23
21

You could write a simple python script to handle the automation of superuser creation. The User model is just a normal Django model, so you'd follow the normal process of writing a stand-alone Django script. Ex:

import django
django.setup()

from django.contrib.auth.models import User

u = User(username='unique_fellow')
u.set_password('a_very_cryptic_password')
u.is_superuser = True
u.is_staff = True
u.save()

You can also pass createsuperuser a few options, namely --noinput and --username, which would let you automatically create new superusers, but they would not be able to login until you set a password for them.

fiveclubs
  • 2,392
  • 2
  • 18
  • 28
Zach Kelling
  • 52,505
  • 13
  • 109
  • 108
  • 2
    Ok for `cretesuperuser`, but how to set the password then? I would like to do that inside a bash script... – caneta Dec 10 '13 at 12:32
16

Current most voted answer:

  • Deletes the user if it exists and as noted by @Groady in the comments you risk unintentionally deleting any associated records via a cascade delete.
  • Checks superuser existence filtering by mail so if two superusers have the same mail god knows which one it deletes.
  • It is cumbersome to update the script parameters: username, password, and mail.
  • Does not log what it did.

An improved version would be:

USER="admin"
PASS="super_password"
MAIL="admin@mail.com"
script="
from django.contrib.auth.models import User;

username = '$USER';
password = '$PASS';
email = '$MAIL';

if User.objects.filter(username=username).count()==0:
    User.objects.create_superuser(username, email, password);
    print('Superuser created.');
else:
    print('Superuser creation skipped.');
"
printf "$script" | python manage.py shell
David Darias
  • 570
  • 6
  • 9
  • 3
    Much cleaner (better) than the accepted answer. You could also have used: `if not User.objects.filter(username = username).exists()`, – Philippe Fanaro Jul 25 '19 at 13:38
8

A solution based on Adam Charnock's approach above is available as a Python package by now. It takes three steps:

  1. Install: pip install django-createsuperuserwithpassword

  2. Activate: INSTALLED_APPS += ("django_createsuperuserwithpassword", )

  3. Apply:

    python manage.py createsuperuserwithpassword \
            --username admin \
            --password admin \
            --email admin@example.org \
            --preserve
    

That's it.

Sebastian
  • 131
  • 2
  • 3
6

I solved this problem like this.

wsgi.py file always runs when django project starts. So I run create super user commands in here if it doesn't exist.

import os

from django.contrib.auth.models import User
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', {settings_file})

application = get_wsgi_application()

users = User.objects.all()
if not users:
    User.objects.create_superuser(username="username", email="user@example.com", password="password", is_active=True, is_staff=True)

A function can be added here. For example; if this "user1" doesn't exist, add "user1".

Sarp
  • 61
  • 1
  • 3
3
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User

class Command(BaseCommand):

    def handle(self, *args, **options):

        # The magic line
        User.objects.create_user(username= 'rmx',
                                email='superuser@super.com',
                                password='rmx55',
                                is_staff=True,
                                is_active=True,
                                is_superuser=True
        )
BackdoorTech
  • 328
  • 6
  • 7
3

I like to use for serverless/docker builds the AppConfig.ready method/event to perform this kind of operations, here's an example:

import logging

from django.apps import AppConfig
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as gettext


class Config(AppConfig):
    name: str = "apps.policy"
    label: str = "policy"
    verbose_name: str = gettext("Policies")

    @classmethod
    def ready(cls):
        user_model = get_user_model()
        log = logging.getLogger(cls.label)

        try:
            if not user_model.objects.filter(username="admin").first():
                log.info("Creating default superuser with user and password: admin")
                user_model.objects.create_superuser('admin', 'admin@admin.admin', 'admin')
        except Exception:
            log.warn(
                "Found an error trying to create the superuser, if you aren't"
                "run the user model migration yet, ignore this message"
            )

And when I first start my project in the database I see:

2021-06-22 06:19:02 policy/info  Creating default superuser with user and password: admin
Performing system checks...

System check identified no issues (1 silenced).
June 22, 2021 - 06:19:02
Django version 3.1.12, using settings 'settings.env.default'
Starting development server at http://0.0.0.0:8027/
Quit the server with CONTROL-C.
Felipe Buccioni
  • 19,109
  • 2
  • 28
  • 28
2

With shell_plus it's much easier actually

echo "User.objects.create_superuser('test@test.com', 'test')" | python manage.py shell_plus

As others mentioned, with Django 3.0 you can pass the credentials via environment variables. However this approach is much more flexible since it allows you to do any other more complicated task like removing all tests users, etc.

Pithikos
  • 18,827
  • 15
  • 113
  • 136
1

I used Tk421 one liner but got an error message as: 1) I think I am using a later version of Django (1.10) Manager isn't available; 'auth.User' has been swapped for 'users.User' 2) the order of the parameters to create_superuser was wrong.

So I replaced it with:

echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email='admin@example.com', is_superuser=True).delete(); User.objects.create_superuser('admin', 'admin@example.com', 'nimda')" | python manage.py shell

and what I as really pleased with is that it works on a heroku deployment as well:

heroku run echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email='admin@example.com', is_superuser=True).delete(); User.objects.create_superuser('admin', 'admin@example.com', 'nimda')" | python manage.py shell

This will work nicely repeatedly. I am using it the beginning of a project so don't worry about the terrible cascaded deletes that might occur later.

I have revisited after some trouble with running this inside local() from fabric. what seemed to be happening is that the pipe symbol mean that it was getting interpreted locally rather than on heroku. To sort this I wrapped in the command in quotes. Then had to used triple double quotes for the python strings inside the single quotes of the whole python command.

heroku run "echo 'from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email="""admin@example.com""", is_superuser=True).delete(); User.objects.create_superuser("""admin""", """admin@example.com""", """nimda""")' | python manage.py shell"
hum3
  • 1,563
  • 1
  • 14
  • 21
1
python manage.py shell -c "from django.contrib.auth.models import User; \
                           User.objects.filter(username='admin1').exists() or \
                           User.objects.create_superuser('admin1',
                           'admin1@example.com', 'admin1')"
Raja R
  • 39
  • 1
  • 3
1

You can create a superuser in a custom command like this:

import os

from django.contrib.auth.models import User
from django.core.management import BaseCommand, call_command

from immo_project import settings


class Command(BaseCommand):
    def handle(self, *args, **options):
        call_command('createsuperuser', interactive=False, username='admin', email='test@example.com')
        user = User.objects.get(username='admin')
        user.set_password('password')
        user.save()
G. Marc
  • 4,987
  • 4
  • 32
  • 49
0

This small python script could create a normal user or a superuser

#!/usr/bin/env python

import os
import sys
import argparse
import random
import string
import django


def main(arguments):

    parser = argparse.ArgumentParser()
    parser.add_argument('--username', dest='username', type=str)
    parser.add_argument('--email', dest='email', type=str)
    parser.add_argument('--settings', dest='settings', type=str)
    parser.add_argument('--project_dir', dest='project_dir', type=str)
    parser.add_argument('--password', dest='password', type=str, required=False)
    parser.add_argument('--superuser', dest='superuser', action='store_true', required=False)

    args = parser.parse_args()

    sys.path.append(args.project_dir)
    os.environ['DJANGO_SETTINGS_MODULE'] = args.settings
    from django.contrib.auth.models import User
    django.setup()

    username = args.username
    email = args.email
    password = ''.join(random.sample(string.letters, 20)) if args.password is None else args.password
    superuser = args.superuser 

    try:
        user_obj = User.objects.get(username=args.username)
        user_obj.set_password(password)
        user_obj.save()
    except User.DoesNotExist:
    if superuser:
            User.objects.create_superuser(username, email, password)
    else:
        User.objects.create_user(username, email, password)

    print password


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

--superuser & --password are not mandatory.

If --superuser is not defined, normal user will be created If --password is not defined, a random password will be generated

    Ex : 
        /var/www/vhosts/PROJECT/python27/bin/python /usr/local/sbin/manage_dja_superusertest.py --username USERNAME --email TEST@domain.tld --project_dir /var/www/vhosts/PROJECT/PROJECT/ --settings PROJECT.settings.env 
Thibault Richard
  • 356
  • 2
  • 11
0

This is what I cobbled together for Heroku post_deploy and a predefined app.json variable:

if [[ -n "$CREATE_SUPER_USER" ]]; then
    echo "==> Creating super user"
    cd /app/example_project/src
    printf "from django.contrib.auth.models import User\nif not User.objects.exists(): User.objects.create_superuser(*'$CREATE_SUPER_USER'.split(':'))" | python /app/example_project/manage.py shell
fi

With this you can have a single env variable:

CREATE_SUPER_USER=admin:admin@example.com:password

I like the shell --command option, but not sure how the get newline character in the command script. Without the newline the if expression results in syntax error.

Janusz Skonieczny
  • 17,642
  • 11
  • 55
  • 63
0

python manage.py shell < mysite/create_superuser.py

mysite/create_superuser.py

from decouple import config
from django.db import IntegrityError

# getting name,email & password from env variables
DJANGO_SU_NAME = config('DJANGO_SU_NAME')
DJANGO_SU_EMAIL = config('DJANGO_SU_EMAIL')
DJANGO_SU_PASSWORD = config('DJANGO_SU_PASSWORD')

try:
    superuser = User.objects.create_superuser(
        username=DJANGO_SU_NAME,
        email=DJANGO_SU_EMAIL,
        password=DJANGO_SU_PASSWORD)
    superuser.save()
except IntegrityError:
    print(f"Super User with username {DJANGO_SU_NAME} is already present")
except Exception as e:
    print(e)
  • More specifically!!! In docker-compose.yml file under django project container: command: > /bin/bash -c "python manage.py shell < mysite/create_superuser.py" – abdulalim Nov 01 '22 at 06:46
0

For those who just want to host a django website on AWS Elastic Beanstalk (even without docker) and are stuck on the superuser part, create a file called 01_migrate.sh in .platform > hooks > postdeploy and input the below:

#!/bin/bash

source /var/app/venv/*/bin/activate && { python migrate.py createsuperuser --noinput; }

You can then add DJANGO_SUPERUSER_PASSWORD, DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_EMAIL to the configuration section of the application environment.

Then add the below to the folder .ebextentions > django.config

container_commands:
    01_chmod1:
         command: "chmod +x .platform/hooks/postdeploy/01_migrate.sh"

That will create your superuser in a secure way, with the same logic you can also run migrations and collectstatic by adding to the 01_migrate.sh file.

jimbo
  • 21
  • 1
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31361735) – ABN Mar 27 '22 at 16:27
0

send command to docker-compose

almost same answer like above.

docker-compose exec service_name sh -c "
from django.contrib.auth.models import User


username = \"admin\"
email = \"admin@example.com\"
password = \"password\"
User.objects.create_superuser(username, email, password)
"

I do not mentioned about validate or check user before creation. if you care about that, check above answers.

Yoooda
  • 31
  • 2
  • 7
0

In my case, we are automating with some bash, docker, helm, we were having some issues escaping some commas and quotes, after some try/error we figured out the easiest way (easiest for us), this single line command based on the doc shared previously did the trick

DJANGO_SUPERUSER_PASSWORD=12345 DJANGO_SUPERUSER_USERNAME=pacho DJANGO_SUPERUSER_EMAIL=pacho@gmail.com python manage.py createsuperuser --noinput
Yor Jaggy
  • 405
  • 4
  • 11
0

The best solution I have found also also personally used is following:

echo "from django.contrib.auth.models import User; User.objects.filter(username='username').exists() or User.objects.create_superuser('username', 'email@mail.com','passswordd' )" | python manage.py shell

All other specified solutions above gave me error that user already exists. I am using this as a shell script to run when even i deploy me new Django API on Kubernetes.

hope it helps someone.

Ali Hamza
  • 121
  • 1
  • 1
  • 5
0

very easy, listen on post syncdb signal and read superuser credentials from a configuration file and apply it.

Check out django-finalware, and its predecessor django-bootup [deprecated]

John Vandenberg
  • 474
  • 6
  • 16
Val Neekman
  • 17,692
  • 14
  • 63
  • 66
-1

Go to command prompt and type:

C:\WINDOWS\system32>pip install django-createsuperuser
Collecting django-createsuperuser
  Downloading https://files.pythonhosted.org/packages/93/8c/344c6367afa62b709adebee039d09229675f1ee34d424180fcee9ed857a5/django-createsuperuser-2019.4.13.tar.gz
Requirement already satisfied: Django>1.0 in c:\programdata\anaconda3\lib\site-packages (from django-createsuperuser) (2.2.1)
Requirement already satisfied: setuptools in c:\programdata\anaconda3\lib\site-packages (from django-createsuperuser) (41.0.1)
Requirement already satisfied: sqlparse in c:\programdata\anaconda3\lib\site-packages (from Django>1.0->django-createsuperuser) (0.3.0)
Requirement already satisfied: pytz in c:\programdata\anaconda3\lib\site-packages (from Django>1.0->django-createsuperuser) (2018.7)
Building wheels for collected packages: django-createsuperuser
  Running setup.py bdist_wheel for django-createsuperuser ... done
  Stored in directory: C:\Users\Arif Khan\AppData\Local\pip\Cache\wheels\0c\96\2a\e73e95bd420e844d3da1c9d3e496c92642a4f2181535440db2
Successfully built django-createsuperuser
Installing collected packages: django-createsuperuser

if not executed the migration then go to django application folder and execute following

  1. python manage.py migrate
  2. python manage.py createsuperuser

then bingo.

sanyassh
  • 8,100
  • 13
  • 36
  • 70
Arif Khan
  • 1
  • 3