好的,所以我正在尝试使用Django创建一个登录。
来自views.py的:
from django.shortcuts import *
from forms import UserRegistrationForm
from django.contrib.auth import authenticate, login
from django.core.mail import send_mail
from django.conf import settings
import pprint
import utils
import models
from django.http import HttpResponse
import views
from django.conf.urls import patterns, url
def login_user(request):
state = "Please log in below..."
username = password = ''
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if not user.is_verified:
state = "Please check your e-mail to verify your account."
elif user.is_active:
login(request, user)
state = "You're successfully logged in!"
else:
state = "Your account is not active, please contact the site admin."
else:
state = "Your username and/or password were incorrect."
return render_to_response('myapp/dashboard.html', {'state': state}, RequestContext(request))
else:
return render_to_response('myapp/login.html', RequestContext(request))
我的登录模板(login.html):
<h3>Login</h3><hr />
<form action="/login/" method="post">
{% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
username:
<input type="text" name="username" value="{{ username }}" /><br />
password:
<input type="password" name="password" value="" /><br />
<input class="btn" type="submit" value="Log In" />
</form>
我正在使用基本的SQLite3来解决所有问题。 python manage.py syncdb运行没有问题
来自settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'tempDB'
}
}
当我登录管理网站时,我看到了用户:
用户名:nick 密码:nick的哈希版本
当我插入一个中断(使用PBD)时,我能够看到应用程序通过login_user视图。
> ...myapp/myapp/views.py(52)login_user()
-> state = "Please log in below..."
(Pdb) n
> ...myapp/myapp/views.py(53)login_user()
-> username = password = ''
(Pdb) print username
*** NameError: name 'username' is not defined
(Pdb) n
> ...myapp/myapp/views.py(55)login_user()
-> if request.POST:
(Pdb) print username
(Pdb) n
> ...myapp/myapp/views.py(56)login_user()
-> username = request.POST.get('username')
(Pdb) print username
(Pdb) n
> ...myapp/myapp/views.py(57)login_user()
-> password = request.POST.get('password')
(Pdb) print username
nick
(Pdb) n
> ...myapp/myapp/views.py(59)login_user()
-> user = authenticate(username=username, password=password)
(Pdb) print password
nick
(Pdb) n
> ...myapp/myapp/views.py(61)login_user()
-> if user is not None:
(Pdb) print user
None
这表明它获取了用户名'nick'和密码'nick'(我设置帐户的设置)但是我遇到的问题是authenticate仍然返回None,这意味着没有设置SOMETHING正确/无效。
在login_user视图之后,'state'显示“您的用户名和/或密码不正确”。正如在views.py中所做的那样。
如果有人能够帮助我,我将不胜感激!
答案 0 :(得分:0)
(也在G +上回复)
从你的pdb会话:
(Pdb) print password
nick
如果发生了什么,那就有问题,你不同意吗? 此外,我将取消vars的初始化并改为:
username = request.POST.get('username')
password = request.POST.get('password')
if username and password:
# Your code
request.POST.get无论如何都会工作(POST总是初始化为QueryDict),如果找不到密钥,则get()返回None,这样你就不会出现任何错误 - 这对你来说可能更容易看看发生了什么。