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

caf*_*991 3 django ajax

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

更新

我使用了 ajax 请求,并在失败时发送了一个重定向,以便在成功时显示无效详细信息错误和 render_to_response。失败工作正常,但成功后我看到的是同一页面上的 render_to_response 发送的模板... .如何应对..

谁能帮我?

Ane*_*pic 5

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

所以代替这个:

return render_to_response("p/home.html", context_dict, context)
Run Code Online (Sandbox Code Playgroud)

你应该做:

return redirect('home')
Run Code Online (Sandbox Code Playgroud)

其中'home'是您的主页视图的 url 名称urls.py

您需要在视图文件的顶部导入此内容:

from django.shortcuts import redirect
Run Code Online (Sandbox Code Playgroud)

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