首页 > 解决方案 > 从 Django views.py 返回 HttpResponse 对象和渲染页面

问题描述

我是 Django 新手,一直在通过修改一些现有代码来学习。respviews.py 文件中的原始代码有一个方法,该方法通过单击按钮 将 HTTP 响应对象(让我们调用 this )返回给浏览器。

我希望能够

  1. 单击该按钮打开一个新页面(我正在使用 render() 函数)

  1. 传递resp给它(这是因为我使用的第 3 方 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

标签: django

解决方案


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

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

推荐阅读