Django登录失败

de1*_*7ed 1 forms authentication django login

我正在尝试创建用户登录视图,并且它一直在失败.这是我的代码:

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))
Run Code Online (Sandbox Code Playgroud)

基本上,我一直在我的网站上打印"FORM NOT VALID",我不知道为什么.请帮忙?谢谢

pet*_*szd 6

这段代码错了:

form = AuthenticationForm(request.POST)
Run Code Online (Sandbox Code Playgroud)

您需要更改为:

form = AuthenticationForm(data=request.POST)
Run Code Online (Sandbox Code Playgroud)

这是因为AuthenticationForm覆盖了__init__方法而构造函数的第一个参数不是data,而是request=None.

一些技巧:

  • 请重新使用包含登录视图的@piquadrat建议.
  • 如果您使用的是Django 1.3,请使用渲染快捷方式而不是render_to_response +传递RequestContext.如果您正在使用Django <1.3 backport渲染快捷方式并使用它.
  • 不要硬编码模板绝对路径; 使用settings.TEMPLATE_DIRS