[英]Django Login failing
我正在尝试制作用户登录视图,并且它一直失败。 这是我的代码:
def userLogin(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
user = authenticate(username = request.POST['username'], password = request.POST['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect("/success")
else:
return render_to_response('/home/dockedin/webapps/linked/myproject/templates/index.html', {'outcome':'Account Disabled'}, context_instance= RequestContext(request))
else:
return render_to_response('/home/dockedin/webapps/linked/myproject/templates/index.html', {'outcome':'Invalid Login'}, context_instance= RequestContext(request))
else:
return render_to_response('/home/dockedin/webapps/linked/myproject/templates/index.html', {'outcome':'FORM NOT VALID?'}, context_instance= RequestContext(request))
else:
form = AuthenticationForm()
return render_to_response('/home/dockedin/webapps/linked/myproject/templates/index.html', {'form':form}, context_instance= RequestContext(request))
基本上,我一直在网站上打印“ FORM NOT VALID”,但不知道为什么。 请帮助? 谢谢
这段代码是错误的:
form = AuthenticationForm(request.POST)
您需要更改为:
form = AuthenticationForm(data=request.POST)
这是因为AuthenticationForm覆盖__init__
方法,并且构造函数的第一个参数不是data
,而是request=None
。
一些技巧:
RequestContext
。 如果您使用的是Django <1.3 backport渲染快捷方式,请使用它。 尝试打印form.errors
以查看验证失败的原因。
顺便说一句,您是否有理由不使用内置的django.contrib.auth.views.login
视图?
您正在错误地接近Django表单的概念。 Django中的Form的想法是,它可以处理POST数据,因此您不必这样做。 这不仅仅是验证数据是否正确。 它们还可以将数据转换为可靠状态。
if request.method == "POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
login(request, form.get_user())
请注意,是否需要手动进行身份验证? 当您检查表单是否有效时,表单实例会进行身份验证。 然后,通过从表单本身中检索用户实例,只需简单地登录用户即可。
您应该很少(如果有的话)必须从视图中访问POST数据。 表单应用于处理,清理,验证和返回有效对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.