authenticate()函数不能正常工作django.contrib.auth

时间:2013-09-13 03:59:45

标签: python django django-authentication

我有一个login_page函数,在这个函数中,authenticate()函数只有在超级用户时才返回用户对象。对于普通用户,它返回None。这不是文档所说的。

def login_page(request):
    if request.user.is_authenticated(): # if user is already logged in
        return HttpResponseRedirect('/') # SHOULD BE DASHBOARD
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            seo_specialist = authenticate(username=username, password=password) #returns None
            if seo_specialist is not None:
                login(request, seo_specialist)
                return HttpResponseRedirect('/') # SHOULD BE DASHBOARD
            else:
                return render(request, 'login.html', {'form': form})
        else:
            return render(request, 'login.html', {'form': form})
    else: 
        form = LoginForm()
        context = {'form': form}
        return render(request, 'login.html', context)

我的代码有什么问题吗?

2 个答案:

答案 0 :(得分:8)

试试这个:

def login_page(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        seo_specialist = authenticate(username=username, password=password)
        if seo_specialist is not None:
            return HttpResponse("Signed in")
        else:
            return HttpResponse("Not signed in")
    else:
        # takes you to sign in form. 

基本上用request.POST替换is_valid和cleaning_data,然后进行身份验证。还要确保你有

from django.contrib.auth import authenticate

位于您的观看次数的顶部。

答案 1 :(得分:0)

这来自Django文档。您似乎尚未通过... authenticate(request,user ...)

中的请求

此示例显示了如何同时使用authenticate()和login():

    from django.contrib.auth import authenticate, login

    def my_view(request):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            # Redirect to a success page.
            ...
        else:
            # Return an 'invalid login' error message.
            ...