Linux shell命令创建python django用户

方式一

  • 使用 --noinput 参数
# 密码是通过 DJANGO_SUPERUSER_PASSWORD 变量来设置,如果变量不存在,则用户可创建成功,但无法登录,直到用户被设置密码方可使用.
export DJANGO_SUPERUSER_PASSWORD=xxxxx
python manage.py createsuperuser --noinput --username test  --email www@mrdoc.fun

方式二

echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('用户名', 'www@mrdoc.fun', '密码')" | python manage.py shell

方式三

  • 增加manage.py的自定义初始化命令,如:initadmin
# 示例:initadmin.py
class Command(BaseCommand):

    def handle(self, *args, **options):
        if Account.objects.count() == 0:
            for user in settings.ADMINS:
                username = user[0].replace(' ', '')
                email = user[1]
                password = 'admin'
                print('Creating account for %s (%s)' % (username, email))
                admin = Account.objects.create_superuser(email=email, username=username, password=password)
                admin.is_active = True
                admin.is_admin = True
                admin.save()
        else:
            print('Admin accounts can only be initialized if no Accounts exist')

Reference Link

posted @ 2021-05-23 18:04  jonnyan  阅读(200)  评论(0编辑  收藏  举报