Python 如何从 django shell 创建用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18503770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:55:04  来源:igfitidea点击:

How to create user from django shell

pythondjangoshelldjango-shell

提问by shifu

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

当我从django-admin用户密码创建用户时是加密的。但是当我从 django shell 创建用户时,用户密码以纯文本格式保存。例子 :

{
    "date_joined": "2013-08-28T04:22:56.322185",
    "email": "",
    "first_name": "",
    "id": 5,
    "is_active": true,
    "is_staff": false,
    "is_superuser": false,
    "last_login": "2013-08-28T04:22:56.322134",
    "last_name": "",
    "password": "pbkdf2_sha256000$iGKbck9CED0bhWrKYiMPNGKhcfPVGal2YP4LkuP3Qwem+2ydswWACk=",
    "resource_uri": "/api/v1/user/5/",
    "username": "user4"
},
{
    "date_joined": "2013-08-29T01:15:36.414887",
    "email": "test@ophio",
    "first_name": "",
    "id": 6,
    "is_active": true,
    "is_staff": true,
    "is_superuser": true,
    "last_login": "2013-08-29T01:15:36.414807",
    "last_name": "",
    "password": "123test",
    "resource_uri": "/api/v1/user/6/",
    "username": "test3"
} 

I am trying to make REST style api for a simple blog app : when i try to insert a user by post request [ by passing JSON ] password is saved as plain text. how to override this behaviour.

我正在尝试为一个简单的博客应用程序制作 REST 风格的 api:当我尝试通过发布请求插入用户时 [通过传递 JSON] 密码被保存为纯文本。如何覆盖此行为。

采纳答案by Daniel Roseman

You should not create the user via the normal User(...)syntax, as others have suggested. You should always use User.objects.create_user(), which takes care of setting the password properly.

您不应该User(...)像其他人建议的那样通过正常语法创建用户。您应该始终使用User.objects.create_user(),它负责正确设置密码。

user@host> manage.py shell
>>> from django.contrib.auth.models import User
>>> user=User.objects.create_user('foo', password='bar')
>>> user.is_superuser=True
>>> user.is_staff=True
>>> user.save()

回答by Snakes and Coffee

You use user.set_passwordto set passwords in the django shell. I'm not even sure if directly setting the password via user.passwordwould even work, since Django expects a hash of the password.

您用于user.set_password在 django shell 中设置密码。我什至不确定通过直接设置密码user.password是否可行,因为 Django 需要密码的哈希值。

The passwordfield doesn't store passwords; it stores them as <algorithm>$<iterations>$<salt>$<hash>, so when it checks a password, it calculates the hash, and compares it. I doubt the user actually has a password whose calculated password hash is in <algorithm>$<iterations>$<salt>$<hash>form.

password字段不存储密码;它将它们存储为<algorithm>$<iterations>$<salt>$<hash>,因此当它检查密码时,它会计算哈希值并进行比较。我怀疑用户是否真的有一个密码,其计算出的密码哈希是<algorithm>$<iterations>$<salt>$<hash>形式。

If you get the jsonwith all the information needed to create the User, you could just do

如果您获得了json创建用户所需的所有信息,您可以这样做

User.objects.create_user(**data)

assuming your passed json is called data.

假设您传递的 json 称为数据。

Note: This will throw an error if you have extra or missing items in data.

注意:如果您在data.

If you really want to override this behavior, you can do

如果你真的想覆盖这个行为,你可以这样做

def override_setattr(self,name,value):
    if name == 'password':
        self.set_password(value)
    else:
        super().__setattr__(self,name,value) #or however super should be used for your version

User.__setattr__ = override_setattr

I haven't tested this solution, but it should work. Use at your own risk.

我还没有测试过这个解决方案,但它应该可以工作。使用风险自负。

回答by Rahul Tanwani

There are couple of way to set password for a django user object from django-shell.

有几种方法可以从 django-shell 为 django 用户对象设置密码。

user = User(username="django", password = "secret")
user.save()

This will store encrypted password.

这将存储加密的密码。

user = User(username="django")
user.set_password("secret")
user.save()

This will store encrypted password.

这将存储加密的密码。

But,

但,

user = User(username="django")
user.password="secret"
user.save()

This will store plain text password. There is no hashing / encryptions applied since you are modifying the property directly.

这将存储纯文本密码。由于您是直接修改属性,因此没有应用散列/加密。

回答by Zargold

Answer for those using django 1.9 or greater since from django.contrib.auth.models import Userhas been deprecated (possibly even earlier) but definitely by 1.9.

那些使用 django 1.9 或更高版本的人的答案from django.contrib.auth.models import User已经被弃用(可能更早),但肯定是 1.9。

Instead do: in bash:

而是这样做:在bash中:

python manage.py shell

In the python shell to create a user with a password:

在python shell中创建一个带密码的用户:

from django.apps import apps
User = apps.get_model('user', 'User')
me = User.objects.create(first_name='john', email='[email protected]') # other_info='other_info', etc.
me.set_password('WhateverIwant')  # this will be saved hashed and encrypted
me.save()

If coming from an API you should probably apply a Form as such:

如果来自 API,您可能应该应用这样的表单:

import json
User = get_model('User')
class UserEditForm(BaseModelForm):
        """This allows for validity checking..."""

        class Meta:
            model = User
            fields = [
                'first_name', 'password', 'last_name',
                'dob', # etc...
            ]
# collect the data from the API:
post_data = request.POST.dict()
data = {
'first_name': post_data['firstName'],
'last_name': post_data['firstName'],
'password': post_data['password'], etc.
}
dudette = User()  # (this is for create if its edit you can get the User by pk with User.objects.get(pk=kwargs.pk))
form = UserEditForm(data, request.FILES, instance=dudette)
if form.is_valid():
    dudette = form.save()
else:
    dudette = {'success': False, 'message': unicode(form.errors)}
return json.dumps(dudette.json())  # assumes you have a json serializer on the model called def json(self):

回答by Adizbek Ergashev

The fastest way creating of super user for django, type in shell:

为django创建超级用户的最快方法,在shell中输入:

python manage.py createsuperuser

回答by Du D.

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()

参考:get_user_model()

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

记得先激活 VirtualEnv,然后运行下面的命令(对于 Linux):

cat create_user.py | python manage.py shell

If you using window then substitute the catcommand with the typecommand

如果您使用 window 然后用type命令替换cat命令

type create_user.py | python manage.py shell

OR for both Linux and Windows

或适用于 Linux 和 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

回答by Cubiczx

To create Users execute:

要创建用户,请执行:

$ python manage.py shell
>>>> from django.contrib.auth.models import User
>>>> user = User.objects.create_user('USERNAME', 'MAIL_NO_REQUIRED', 'PASSWORD')