How to automate createsuperuser on django?

后端 未结 16 1569
情歌与酒
情歌与酒 2020-11-29 15:57

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?

16条回答
  •  清歌不尽
    2020-11-29 16:25

    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
    

提交回复
热议问题