我想在django
上自動運行migrate.py createsuperuser
,但它認爲沒有辦法設置默認密碼。如何在django上自動創建createsuperuser?
我怎樣才能得到這個?它必須獨立於django數據庫。
我想在django
上自動運行migrate.py createsuperuser
,但它認爲沒有辦法設置默認密碼。如何在django上自動創建createsuperuser?
我怎樣才能得到這個?它必須獨立於django數據庫。
你可以編寫一個簡單的python腳本來處理超級用戶創建的自動化。 User
模型只是一個普通的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()
您也可以通過createsuperuser
幾個選項,即--noinput
和--username
,這將讓你自動創建新的超級用戶,但他們將無法登錄,直到你爲他們設置密碼。
確定'cretesuperuser',但是如何設置密碼呢?我願做一個bash腳本... – caneta 2013-12-10 12:32:13
Django的1.4+內,修改爲http://stackoverflow.com/a/21149868/91365給出 – 2014-05-22 15:51:03
非常容易,可以偵聽後syncdb信號並從配置文件讀取超級用戶憑證並應用它。
checkout django-bootup
鏈接不提供任何更多 – Tk421 2014-09-29 01:03:55
它於:https ://github.com/un33k/django-bootup - 但這表示棄用贊成https:// github。com/un33k/django-finalware – stephendwolff 2017-03-03 16:32:25
這裏有一個簡單的版本的腳本來創建一個超級用戶:
echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', '[email protected]', 'pass')" | python manage.py shell
編輯
正如評論,下面的命令刪除建議,並創建超級用戶因此命令總是適用於每一個版本:
echo "from django.contrib.auth.models import User; User.objects.filter(email='[email protected]').delete(); User.objects.create_superuser('admin', '[email protected]', 'nimda')" | python manage.py shell
超級用戶試圖在heroku中創建超級用戶並且您的網絡塊端口爲5000 – Vic 2016-06-09 05:40:09
我將刪除現有的超級用戶,因此每個構建都有效: '''echo「from django.contrib .auth.models import User; User.objects.filter(email='[email protected]')。delete(); User.objects.create_superuser('[email protected]','admin','nimda') 「|蟒蛇manage.py外殼 ''' – Montaro 2016-11-01 15:04:47
個人而言,我不認爲刪除每個版本的用戶是一個好主意。您可能會無意中通過級聯刪除刪除任何關聯的記錄。如果用戶已經存在(或更新現有的用戶記錄),則更安全的選擇是簡單地解救出來。 – Groady 2017-01-07 01:15:21
當前最票已投票回答:
的改進版本是:
USER="admin"
PASS="super_password"
MAIL="[email protected]"
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
這個小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都不是強制性的。
如果沒有定義--superuser,普通用戶將創建 如果沒有定義 - 密碼,隨機密碼生成
Ex :
/var/www/vhosts/PROJECT/python27/bin/python /usr/local/sbin/manage_dja_superusertest.py --username USERNAME --email [email protected] --project_dir /var/www/vhosts/PROJECT/PROJECT/ --settings PROJECT.settings.env
我自己尋找一個答案。我決定創建延伸基部createsuperuser
命令(GitHub)一個Django命令:
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()
實施例使用:
./manage.py createsuperuser2 --username test1 --password 123321 --noinput --email '[email protected]'
這具有仍然支持的默認命令的使用,同時還允許非優勢交互式用於指定密碼。
我用「./manage.py殼-c」:
./manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_superuser('admin', '[email protected]', 'adminpass')"
這不使用額外的回聲,這有,你可以把它傳遞給一個泊塢窗容器執行的好處。沒有它你進入報價逃離地獄需要使用SH -c「......」。
記住,第一自帶的用戶名,比電子郵件。
我使用了Tk421的一個班輪,但收到了一條錯誤消息:1)我認爲我使用的是Django的更高版本(1.10)Manager isn't available; 'auth.User' has been swapped for 'users.User'
2)參數的順序爲create_superuser是錯誤的。
所以我取代它:
echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email='[email protected]', is_superuser=True).delete(); User.objects.create_superuser('admin', '[email protected]', 'nimda')" | python manage.py shell
和我的真的很高興的是,它可以在一個Heroku的部署,以及:
heroku run echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email='[email protected]', is_superuser=True).delete(); User.objects.create_superuser('admin', '[email protected]', 'nimda')" | python manage.py shell
這將很好地反覆工作。我使用它是項目的開始,所以不要擔心後面可能發生的可怕級聯刪除。
我後一些麻煩與織物運行這個內部本地()已經重新審查。似乎正在發生的事情是,管道符號意味着它在本地而不是在heroku上進行解釋。爲了排序這個,我用引號包裹了命令。然後不得不在整個python命令的單引號內使用三重雙引號。
heroku run "echo 'from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email="""[email protected]""", is_superuser=True).delete(); User.objects.create_superuser("""admin""", """[email protected]""", """nimda""")' | python manage.py shell"
這是我拼湊起來的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
有了這個,你可以有一個環境變量:
CREATE_SUPER_USER=admin:[email protected]:password
我喜歡shell --command選項,但不知道如何在命令腳本中獲取換行符。沒有換行符,if
表達式會導致語法錯誤。
有你看着剛剛保存您創建一個超級夾具和使用manage.py加載它? – turbotux 2017-02-27 23:01:18