如何从django shell创建用户

shi*_*ifu 40 python django shell django-shell

当我从django-admin用户密码创建用户时,会加密.但是当我从django shell创建用户时,user-pasword以纯文本格式保存.示例:

{
    "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_sha256$10000$iGKbck9CED0b$6hWrKYiMPNGKhcfPVGal2YP4LkuP3Qwem+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"
} 
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*man 105

您不应该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()
Run Code Online (Sandbox Code Playgroud)

  • 这个神奇的User对象来自哪里?在给出代码样本时没有那个关键的'进口'位的H8.`django.contrib.auth.models` (9认同)
  • `create_user()`的文档:https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#django.contrib.auth.models.CustomUserManager.create_user (4认同)
  • 我不明白你的"完整问题"与我的答案有什么冲突.如果需要在代码中创建用户,则应使用`User.objects.create_user()`. (2认同)
  • 这可以简化为`from django.contrib.auth.models import User; User.objects.create_superuser('foo', password='bar')`。 (2认同)
  • 如果您定义了自己的用户,则需要执行“from django.contrib.auth import get_user_model”,然后执行“User = get_user_model()” (2认同)

Adi*_*hev 13

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

python manage.py createsuperuser
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法以非交互方式做到这一点? (3认同)
  • @ChandanPurohit,您不应该在代码中使用它,您可以使用此命令从终端创建用户。 (2认同)

Du *_* D. 10

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()
Run Code Online (Sandbox Code Playgroud)

Ref: get_user_model()

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

cat create_user.py | python manage.py shell
Run Code Online (Sandbox Code Playgroud)

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

type create_user.py | python manage.py shell
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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.


Zar*_*old 5

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

相反,在 bash 中:

python manage.py shell
Run Code Online (Sandbox Code Playgroud)

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

from django.apps import apps
User = apps.get_model('user', 'User')
me = User.objects.create(first_name='john', email='johnsemail@email.com') # other_info='other_info', etc.
me.set_password('WhateverIwant')  # this will be saved hashed and encrypted
me.save()
Run Code Online (Sandbox Code Playgroud)

如果来自 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):
Run Code Online (Sandbox Code Playgroud)