如何在django中重定向请求对象

时间:2014-07-15 16:24:39

标签: ajax django

我正面临着关于django中重定向的问题。我正在使用ajax调用登录,作为回报,我在失败时获得了json,并且在模板上成功了。

但是在成功时,响应将呈现为html,而不是使用render_to_response重定向到主页。

我试过

使用HttpResponseRedirect我没有得到请求对象,因此我无法获得我要求的会话参数。

注意:这可能有一些错别字,因为我重命名了一些保密变量。

查看

def sign_in(request):
    """
    :param request: data(json)
    """
    response_data = None
    if request.method == 'POST':
        print "Request Landed"
        data = request.POST.get('data', None)
        data = json.loads(data)
        username = data.get("username", None)
        password = data.get("password", None)
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                context = RequestContext(request)
                context_dict = {}
                request.session['username'] = username
                request.session['dd_id'] = str(P.objects.get(username=username).dd_id)
                return render_to_response("p/home.html", context_dict, context)
            else:
                response_data = json.dumps({'status': 'NOT OK', 'reason_phrase': 'Account confirmation is pending at '
                                                                                 'your end.Please check your email '
                                                                                 'address for confirmation link.'})
        else:
            response_data = json.dumps({'status': 'NOT OK', 'reason_phrase': 'Invalid Credentials!'})
    else:
        response_data = json.dumps({'status': 'NOT OK', 'reason_phrase': 'Invalid Request type!'})
    return generate_response(response_data=response_data)

更新

我使用ajax请求并在json失败时发送失败重定向以显示无效详细信息错误,并在成功的情况下发送render_to_response.Failure工作正常但成功后我正在查看由render_to_response在同一页面上发送的模板....如何应对......

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

将其呈现为HTML的原因是因为您使用了render_to_response ......这就是它的作用:)

所以不要这样:

return render_to_response("p/home.html", context_dict, context)

你应该这样做:

return redirect('home')

其中'home'urls.py

中主页视图的网址名称

您需要在视图文件的顶部进行此导入:

from django.shortcuts import redirect
在您的主视图中,您将可以访问所需的请求对象和会话数据

相关问题