如何在Django中以编程方式验证用户身份?

时间:2011-10-25 17:41:30

标签: python django authentication

如何在Django中以编程方式登录用户?我有用户的用户名和密码。有没有让我让他登录的方法?

3 个答案:

答案 0 :(得分:41)

除了“以编程方式”之外别无他法。当然,这是documented

from django.contrib.auth import authenticate, login
user = authenticate(username = username, password = password)
if user is not None:
    login(request, user)

答案 1 :(得分:5)

在以编程方式记录用户时,请注意,您可能会收到错误“user has no attribute "backend"。如果以前没有发生过,你也必须设置后端。 Project that uses this和一些示例代码:

def splash_register(request):
  if request.session.get('beta'):

    if request.method=='POST':
        userform=MyUserCreationForm(request.POST)
        if userform.is_valid():
            #username of <30 char is required by Django User model.  I'm storing username as a hash of user email 

            user=userform.save(commit=False)
            user.username=hash(user.email)
            user.backend='django.contrib.auth.backends.ModelBackend'
            user.save()


            username=user.username
            password=str(userform.cleaned_data['password'])
            auth.login(request, user)
            request.session['first_visit']=True
            return HttpResponseRedirect("/")
        else:
            userform=MyUserCreationForm(request.POST)
            return render_to_response("website/splash_register.html", {'userform':userform}, context_instance=RequestContext(request))
    return render_to_response("website/splash_register.html", context_instance=RequestContext(request))     
else:
    return HttpResponseRedirect('/splash/')

答案 2 :(得分:0)

接受的答案肯定有效,但是,我更喜欢使用内置于auth形式的Django,例如AuthenticationForm.clean

以下是显示重要部分的代码段

authentication

这种方法的主要区别在于User.is_active方法为您调用{{1}}函数,并为您检查{{1}}。