3

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

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)

我的代码有什么问题吗?

4

2 回答 2

12

试试这个:

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和cleaned_data,然后进行身份验证。还要确保你有

from django.contrib.auth import authenticate

在您的视图顶部。

于 2013-09-17T22:45:26.193 回答
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.
            ...
于 2020-10-08T14:46:42.713 回答