如何在Django中创建用户?


87

我正在尝试通过以下代码在Django项目中创建新用户,但突出显示的行会引发异常。

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed

    **user = User.objects.create_user(userName, userMail, userPass)**
    user.save()

    return render_to_response('home.html', context_instance=RequestContext(request))

有什么帮助吗?


6
什么样的例外?
塞萨尔

2
@ user1364223异常回溯?
约瑟夫·维克多·扎米特

我认为User.objects.create应该可以工作。docs.djangoproject.com/en/1.4/ref/models/querysets/#create
iJK 2012年

Answers:


181

在Django中创建用户的正确方法是使用create_user函数。这将处理密码的哈希等。

from django.contrib.auth.models import User
user = User.objects.create_user(username='john',
                                 email='jlennon@beatles.com',
                                 password='glass onion')

这会哈希密码吗?
mp3por 2016年

8
@ mp3por-是的。对于完整的文档,去这里docs.djangoproject.com/en/1.9/ref/contrib/auth/...
keithhackbarth

2
我如何/在哪里运行?如果我只运行该代码,我将得到django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.编辑:这有效DJANGO_SETTINGS_MODULE=app.settings.dev python manage.py shell < register-user.py
citynorman

3
作为更现代的Django的更新,请使用from django.contrib.auth import get_user_modeluser = get_user_model().objects.create_user(...
Mark Chackerian

@keithhackbarth我应该在django文件结构中的哪个文件中插入此代码?
Hangon

23

您是否已确认传递的是实际值None

from django.shortcuts import render

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed
    if userName and userPass and userMail:
       u,created = User.objects.get_or_create(userName, userMail)
       if created:
          # user was created
          # set the password here
       else:
          # user was retrieved
    else:
       # request was empty

    return render(request,'home.html')

1
如果它们为None,.is_valid()方法是否会失败?
mp3por

11

使用批量创建用户 set_password

我要创建几个测试用户,bulk_create速度要快得多,但是我们不能使用create_user它。

set_password 是生成哈希密码的另一种方法:

def users_iterator():
    for i in range(nusers):
        is_superuser = (i == 0)
        user = User(
            first_name='First' + str(i),
            is_staff=is_superuser,
            is_superuser=is_superuser,
            last_name='Last' + str(i),
            username='user' + str(i),
        )
        user.set_password('asdfqwer')
        yield user

class Command(BaseCommand):
    def handle(self, **options):
        User.objects.bulk_create(iter(users_iterator()))

有关密码哈希的特定问题:如何在Django中使用Bcrypt加密密码

在Django 1.9中测试。


1
比接受的要好得多;如果您正在考虑以编程方式添加用户,则可能需要自动执行某些操作以用于更多用途。
斯瓦沃米尔Lenart

5

如果您正常创建用户,则将无法登录,因为密码创建方法可能有所不同。您可以使用默认的注册表单

from django.contrib.auth.forms import UserCreationForm

您也可以扩展

from django.contrib.auth.forms import UserCreationForm

class UserForm(UserCreationForm):
    mobile = forms.CharField(max_length=15, min_length=10)
    email = forms.EmailField(required=True)
    class Meta:
        model = User
        fields = ['username', 'password', 'first_name', 'last_name', 'email', 'mobile' ]

然后在视图中使用此类

class UserCreate(CreateView):
    form_class = UserForm
    template_name = 'registration/signup.html'
    success_url = reverse_lazy('list')

    def form_valid(self, form):
        user = form.save()

1
我认为通过扩展Forms.ModelForm创建UserForm时会出错。我认为应该改为扩展UserCreationForm
vladimir.gorea,

另外,UserCreate类视图的form_class不应为UserForm吗?
vladimir.gorea '18
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.