简体   繁体   English

验证()功能不起作用 django.contrib.auth

[英]authenticate() function not working django.contrib.auth

I have a login_page function and in this function the authenticate() function returns a user object only if it is a superuser.我有一个 login_page 函数,在这个函数中,只有当它是超级用户时,authenticate() 函数才返回一个用户对象。 For normal user, it returns None.对于普通用户,它返回 None。 Which is not as the documentation says.这不像文档所说的那样。

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)

Is there anything wrong with my code?我的代码有什么问题吗?

Try this:试试这个:

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. 

Basically replace is_valid and cleaned_data with request.POST and then authenticate.基本上用 request.POST 替换 is_valid 和cleaned_data,然后进行身份验证。 Also make sure you have还要确保你有

from django.contrib.auth import authenticate

at the top of your views.在您的意见的顶部。

This is from django documentation.这是来自 Django 文档。 You seem to not have passed the request in ...authenticate(request, user...)您似乎没有通过 ...authenticate(request, user...) 中的请求

This example shows how you might use both authenticate() and login():这个例子展示了如何同时使用 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.
            ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM