为什么用户身份验证失败?

时间:2017-09-17 20:44:16

标签: django django-authentication

我正在尝试使用django身份验证系统构建登录页面 以下是观点

from django.contrib import auth
def auth_view(request):
    username = request.POST.get('username','')
    password = request.POST.get('password','')
    print request.POST
    user = auth.authenticate(username=username, password=password)  #returns user object if match else None
    if user is not None:
        auth.login(request, user)  #make user status as logged in now using django login function
        return HttpResponseRedirect('/todos')
    else:
        return HttpResponseRedirect('/accounts/invalid')

的login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login page</title>
</head>
<body>
<h2>login page</h2>
<hr>
<form action="/accounts/auth/" method="post">{% csrf_token %}
    username: <input type="text" name="username" value="" id="username"><br>
    password: <input type="password" name="password" value="" id="password"><br>
    <input type="submit" value="Login">

</form>

</body>
</html>

urls.py

 ...
 urlpatterns = [
     url(r'^admin/', admin.site.urls),
     url(r'^', include('invoices.urls')),
     url(r'^todos/', include('todos.urls')),
     url(r'^accounts/login/$', todos.views.login, name='login'),
     url(r'^accounts/auth/$', todos.views.auth_view, name='auth_view'),
     url(r'^accounts/logout/$', todos.views.logout, name='logout'),
     url(r'^accounts/loggedin/$',todos.views.loggedin, name='loggedin'),
     url(r'^accounts/invalid/$', todos.views.invalid_login, name='invalid_login'),

]

enter image description here

即使用户/密码正确,变量user也会返回None。当我将此行user = auth.authenticate(username=username, password=password)更改为实际用户和密码时,例如。 user = auth.authenticate(username="peter", password="P@$w0rD275")已成功登录

命令行输出

>>>result=auth.authenticate(username='admin', password='adkd92')
>>>print result
None
>>>result=auth.authenticate(username='admin', password='admin123')
>>>print result
admin

1 个答案:

答案 0 :(得分:1)

也许您有一个简单的拼写错误,在以下行的末尾有额外的逗号,

username = request.POST.get('username',''),  # <---
password = request.POST.get('password',''),  # <---

删除它,我猜应该没问题。