如果我使用render_to_response,是否需要HttpRequest对象?

时间:2012-04-26 22:04:17

标签: python django http authentication

Django告诉我我的登录视图没有返回HttpResponse对象:

The view accounts.views.login didn't return an HttpResponse object.

但是,我到处都在使用render_to_response(),如果没有得到回复,视图就无法完成解析。这是代码:

def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    auth_login(request, user)
                    render_to_response('list.html')
                else:
                    error = "It seems your account has been disabled."
                    render_to_response('list.html', {'error': error})
            else:
                error = "Bad login information. Give it another go."
                render_to_response('list.html', {'error': error})
        else:
            error = "Bad login information. Give it another go."
            render_to_response('list.html', {'error': error})
    else:
        error = "Whoa, something weird happened. You sure you're using the form on our site?"
        render_to_response('list.html', {'error': error})

我确信代码可以更高效(渲染次数更少),但这应该可行,对吗?

2 个答案:

答案 0 :(得分:5)

您错过了返回

return render_to_response('list.html', {'error': error})

答案 1 :(得分:2)

您需要返回render_to_response的响应。我建议你进行一些代码改进:

def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    auth_login(request, user)
                    return render_to_response('list.html')
                else:
                    error = "It seems your account has been disabled."
            else:
                error = "Bad login information. Give it another go."
        else:
            error = "Bad login information. Give it another go."
    else:
        error = "Whoa, something weird happened. You sure you're using the form on our site?"
    return render_to_response('list.html', {'error': error})