从Django views.py返回HttpResponse对象并渲染页面

时间:2019-03-25 12:31:55

标签: django

我是Django的新手,已经通过修改一些现有代码来学习。原始代码位于views.py文件中,只需单击一下按钮,该方法便会向浏览器返回HTTP响应对象(称为resp)。

我希望能够

  1. 单击该按钮即可打开一个新页面(我正在使用render()函数进行此操作)

以及

  1. resp传递给它(这是因为我正在使用的第三方API需要此HttpResponse对象才能起作用)。

反正我可以这样做吗?我曾想过将resp作为context函数中render()参数的一部分进行传递,但是我不明白如何从此context字典中获取值,并且然后将其返回到浏览器。

编辑:这是views.py文件中的代码:

def call(request):
    """Returns TwiML instructions to Twilio's POST requests"""
    response = Dial(caller_id=settings.TWILIO_NUMBER)

    # If the browser sent a phoneNumber param, we know this request
    # is a support agent trying to call a customer's phone
    if 'phoneNumber' in request.POST:
        response.number(request.POST['phoneNumber'])
    else:
        # Otherwise we assume this request is a customer trying
        # to contact support from the home page
        response.client('support_agent')

    response = str(response)
    probe = response.find(">")
    response = response[:probe+1] + "<Response>" + response[probe+1:] + "</Response>"
    print('response:', response)
    context = {'response': HttpResponse(response)}
    return render(request, 'browser_calls/call_in_progress.html', context)  # originally HttpResponse(response) was being returned here because that was required for the call to be placed

1 个答案:

答案 0 :(得分:0)

您可以做的是使用locals()返回该范围内的所有变量

context = locals()
return render(request, template, context)