I want to auto run manage.py createsuperuser
on django
but it seams that there is no way of setting a default password.
我想自动运行管理。py在django上创建了一个createsuperuser,但是没有办法设置默认密码。
How can I get this? It has to be independent on the django database.
我怎么能得到这个?它必须独立于django数据库。
9 个解决方案
#1
91
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:
如果您直接引用用户,那么在AUTH_USER_MODEL设置被更改为不同用户模型的项目中,您的代码将无法工作。创建用户的更一般的方法是:
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
#2
18
I use './manage.py shell -c':
我使用“。/管理。py壳- 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.
这并不使用额外的echo,它的好处是您可以将它传递给docker容器以执行。不需要使用sh -c "…"这让你陷入逃避地狱的境地。
And remember that first comes username, than the email.
记住,首先是用户名,而不是电子邮件。
#3
15
I was searching for an answer to this myself. I decided to create a Django command which extends the base createsuperuser
command (GitHub):
我自己在寻找答案。我决定创建一个Django命令,该命令扩展了基本createsuperuperuser命令(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.
这具有支持默认命令使用的优点,同时也允许非交互式地用于指定密码。
#4
11
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:
您可以编写一个简单的python脚本来处理超级用户创建的自动化。用户模型只是一个普通的Django模型,所以您应该遵循编写独立的Django脚本的正常过程。例:
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.
您还可以向createsuperuser传递一些选项,即noinput和username,这样您就可以自动创建新的超级用户,但是在您为他们设置密码之前,他们是无法登录的。
#5
5
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.
- 如果用户存在,则删除该用户。正如@Groady在评论中指出的,您可能会通过级联删除无意地删除任何相关记录。
- 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
#6
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.
我使用了Tk421一行代码,但得到了一个错误消息:1)我认为我正在使用Django (1.10) Manager的一个较晚版本不可用;的身份验证。用户已被替换为用户。User' 2) create_superuser参数的顺序是错误的。
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部署上发挥作用:
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.
我在使用fabric在local()中运行此命令时遇到了一些麻烦,之后再次访问了它。似乎正在发生的是,管道符号意味着它在本地被解释,而不是在heroku上。为了对这个进行排序,我用引号括起来。然后必须在整个python命令的单引号中对python字符串使用三重双引号。
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"
#7
0
very easy, listen on post syncdb signal and read superuser credentials from a configuration file and apply it.
非常简单,监听post syncdb信号并从配置文件中读取超级用户凭证并应用它。
checkout django-bootup
结帐django-bootup
https://github.com/un33k/django-bootup/blob/master/README
https://github.com/un33k/django-bootup/blob/master/README
#8
0
This small python script could create a normal user or a superuser
这个小的python脚本可以创建一个普通用户或超级用户
#!/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.
——superuser &——密码不是强制性的。
If --superuser is not defined, normal user will be created If --password is not defined, a random password will be generated
如果—superuser未定义,则创建普通用户;如果—密码未定义,则生成随机密码
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
#9
0
This is what I cobbled together for Heroku post_deploy and a predefined app.json variable:
这就是我为Heroku post_deploy和预定义的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 a single env variable:
有了这个,你可以有一个单一的env变量:
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.
我喜欢shell——命令选项,但不确定在命令脚本中如何获得换行符。如果没有换行,if表达式会导致语法错误。
#1
91
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:
如果您直接引用用户,那么在AUTH_USER_MODEL设置被更改为不同用户模型的项目中,您的代码将无法工作。创建用户的更一般的方法是:
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
#2
18
I use './manage.py shell -c':
我使用“。/管理。py壳- 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.
这并不使用额外的echo,它的好处是您可以将它传递给docker容器以执行。不需要使用sh -c "…"这让你陷入逃避地狱的境地。
And remember that first comes username, than the email.
记住,首先是用户名,而不是电子邮件。
#3
15
I was searching for an answer to this myself. I decided to create a Django command which extends the base createsuperuser
command (GitHub):
我自己在寻找答案。我决定创建一个Django命令,该命令扩展了基本createsuperuperuser命令(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.
这具有支持默认命令使用的优点,同时也允许非交互式地用于指定密码。
#4
11
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:
您可以编写一个简单的python脚本来处理超级用户创建的自动化。用户模型只是一个普通的Django模型,所以您应该遵循编写独立的Django脚本的正常过程。例:
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.
您还可以向createsuperuser传递一些选项,即noinput和username,这样您就可以自动创建新的超级用户,但是在您为他们设置密码之前,他们是无法登录的。
#5
5
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.
- 如果用户存在,则删除该用户。正如@Groady在评论中指出的,您可能会通过级联删除无意地删除任何相关记录。
- 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
#6
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.
我使用了Tk421一行代码,但得到了一个错误消息:1)我认为我正在使用Django (1.10) Manager的一个较晚版本不可用;的身份验证。用户已被替换为用户。User' 2) create_superuser参数的顺序是错误的。
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部署上发挥作用:
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.
我在使用fabric在local()中运行此命令时遇到了一些麻烦,之后再次访问了它。似乎正在发生的是,管道符号意味着它在本地被解释,而不是在heroku上。为了对这个进行排序,我用引号括起来。然后必须在整个python命令的单引号中对python字符串使用三重双引号。
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"
#7
0
very easy, listen on post syncdb signal and read superuser credentials from a configuration file and apply it.
非常简单,监听post syncdb信号并从配置文件中读取超级用户凭证并应用它。
checkout django-bootup
结帐django-bootup
https://github.com/un33k/django-bootup/blob/master/README
https://github.com/un33k/django-bootup/blob/master/README
#8
0
This small python script could create a normal user or a superuser
这个小的python脚本可以创建一个普通用户或超级用户
#!/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.
——superuser &——密码不是强制性的。
If --superuser is not defined, normal user will be created If --password is not defined, a random password will be generated
如果—superuser未定义,则创建普通用户;如果—密码未定义,则生成随机密码
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
#9
0
This is what I cobbled together for Heroku post_deploy and a predefined app.json variable:
这就是我为Heroku post_deploy和预定义的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 a single env variable:
有了这个,你可以有一个单一的env变量:
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.
我喜欢shell——命令选项,但不确定在命令脚本中如何获得换行符。如果没有换行,if表达式会导致语法错误。