How to automate createuperuser on django?

I want to automatically run manage.py createsuperuser on django but it seems that there is no way to set a default password.

How can i get this? It must be independent of the django database.

+96
django
Jun 05 2018-11-11T00:
source share
12 answers

If you refer to the user directly, your code will not work in projects in which the AUTH_USER_MODEL parameter has been changed to another user model. A more general way to create a user:

 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 RESPONSE

Here is a simple version of the script for creating superuser:

 echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" | python manage.py shell 
+124
Sep 29 '14 at 1:08
source share

I searched for the answer myself. I decided to create a Django command that extends the base createsuperuser ( GitHub ) command:

 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() 

Usage example:

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

This has the advantage that it still supports the use of the default command, and also allows non-interactive use for specifying a password.

+32
Feb 27 '17 at 16:59
source share

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

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

This does not use additional echo, it gives the advantage that you can pass it to the Docker container for execution. Without the need to use sh -c "...", which leads you to the fact that you are moving away from hell.

And remember, the username comes first , not the email.

If you have a custom user model, you need to import it, not auth.models.User

+30
Mar 15 '17 at 14:20
source share

You can write a simple python script to handle the automation of creating a superuser. The User model is just a normal Django model, so you should follow the normal process of writing a standalone Django script. Example:

 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 several parameters, namely --noinput and --username , which will allow you to automatically create new superusers, but they will not be able to log in until you set a password for them.

+13
Jun 05 '11 at 17:13
source share

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

Your data migration will 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 your first migration def generate_superuser(apps, schema_editor): from django.contrib.auth.models import User DJANGO_DB_NAME = os.environ.get('DJANGO_DB_NAME', "default") 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 this helps!

+10
Nov 30 '18 at 10:03
source share

Current most voted answer:

  • Deletes the user if he exists, and as @Groady noted in the comments, you risk unintentionally deleting any related entries through cascading deletion.
  • Checks the filtering of the existence of the superuser by mail, so if two superusers have the same mail god, he knows which one he is deleting.
  • It’s inconvenient to update script parameters: username, password and mail.
  • Not logging what he did.

Enhanced Version:

 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 
+8
Jan 10 '17 at 19:48
source share

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

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 like so much is that it works with the deployment of heroku too:

 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 repeatedly. I use it at the beginning of the project, so don’t worry about scary cascading deletions that may occur later.

I changed my mind after some problems running this inside local () from a fabric. what seemed to be happening was that the pipe symbol means that it is interpreted locally and not on the hero. To sort this, I wrapped the command in quotation marks. Then I had to use triple double quotes for python strings inside the single quotes of the entire 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" 
+1
Jun 14 '17 at 15:10
source share

very simple, listen to the post syncdb signal and read the superuser credentials from the configuration file and apply it.

checkout django-bootup

https://github.com/un33k/django-bootup/blob/master/README

0
Nov 12 2018-11-11T00:
source share

This little python script can create a regular user or 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 and --password are optional.

If --superuser is not defined, a regular user will be created. If -password is not defined, a random password will be created

  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 
0
Jan 31 '17 at 15:43
source share

This is what I put together for Heroku post_deploy and the predefined app.json :

 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 one env variable:

 CREATE_SUPER_USER=admin:admin@example.com:password 

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

0
Nov 24 '17 at 16:03
source share

Go to the command line and enter:

 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 the migration failed, go to the django application folder and follow these steps.

  1. python manage.py migrate
  2. python manage.py creates superuser

then bingo.

0
May 27 '19 at 16:37
source share

A solution based on the approach of Adam Charnock above is now available as a Python package. Three steps are required:

  1. Install: pip install django-createsuperuserwithpassword

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

  3. Use:

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

It.

0
Jun 10 '19 at 15:52
source share



All Articles