Reputation: 3274
i am trying to build login page using django authentication system below is the views
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'),
]
The variable user
returns None
even if the user/password is correct.when i change this line user = auth.authenticate(username=username, password=password)
to actual user and password eg. user = auth.authenticate(username="peter", password="P@$w0rD275")
it is successfully logged in
command line out put
>>>result=auth.authenticate(username='admin', password='adkd92')
>>>print result
None
>>>result=auth.authenticate(username='admin', password='admin123')
>>>print result
admin
Upvotes: 1
Views: 80
Reputation: 39649
Perhaps you have a simple typo, you have extra comma ,
at end of following lines:
username = request.POST.get('username',''), # <---
password = request.POST.get('password',''), # <---
Remove it and it should be fine I guess.
Upvotes: 1