How to create user from django shell

前端 未结 7 466
借酒劲吻你
借酒劲吻你 2021-01-30 04:13

When i create user from django-admin user password\'s are encrypted . but when i create user from django shell user-pasword is saved in plain text . Example :

相关标签:
7条回答
  • 2021-01-30 04:39

    To automate the script you can use the pipe feature to execute the list of commands without having to type it out every time.

    // content of "create_user.py" file
    from django.contrib.auth import get_user_model
    
    # see ref. below
    UserModel = get_user_model()
    
    if not UserModel.objects.filter(username='foo').exists():
        user=UserModel.objects.create_user('foo', password='bar')
        user.is_superuser=True
        user.is_staff=True
        user.save()
    

    Ref: get_user_model()

    Remember to activate VirtualEnv first, then run command below (for Linux):

    cat create_user.py | python manage.py shell
    

    If you using window then substitute the cat command with the type command

    type create_user.py | python manage.py shell
    

    OR for both Linux and Windows

    # if the script is not in the same path as manage.py, then you must 
    #    specify the absolute path of the "create_user.py" 
    python manage.py shell < create_user.py
    

    Pitfall: don't include blank lines in any blocks, think of it as you pasting your code in a repl. If you have empty line in a block it won't work.

    0 讨论(0)
提交回复
热议问题