【问题标题】:Returning python object in httpresponse在httpresponse中返回python对象
【发布时间】:2014-02-19 20:39:35
【问题描述】:

我在视图中有一个返回对象的 python 函数,现在我想从另一个实际返回 HTTPResponse 的函数调用这个函数。如何同时返回 python 对象和 AJAX 响应? 第一个方法返回 python 对象。

def Populate_Config_Resources():
    data = ResourceManager.objects.filter(verified = 1)
    return data

第二种方法返回httpresponse。

def Update_ResourceManager(request):
    try:
        do something...

    except Exception,e:
        return HttpResponse(e)

    # here I call that function.
    config_data = Populate_Config_Resources()
    return HttpResponse('success')

【问题讨论】:

  • 这个问题有点混乱。您似乎没有在任何地方使用模板 - 您需要将对象传递给模板渲染函数。
  • Roseman,我确实使用了一个模板,但我没有将它包含在我的帖子中,因为我的问题是发送我无法执行的对象,一旦我成功发送它我会迭代在模板中覆盖它。尽管如此,谢谢你,下次我问这样的问题时,我会从我的模板中发布代码。 :)

标签: python django


【解决方案1】:

如果您想要该返回值的 AJAX 响应,请使用:

return HttpResponse(json.dumps(config_data), content_type="application/json")

或者如果您使用的是模板:

template = loader.get_template('config.html')
context = RequestContext(request, {"config_data": config_data})
return HttpResponse(template.render(context))

【讨论】:

  • 这应该是mimetype,而不是content_type。否则你会得到TypeError: __init__() got an unexpected keyword argument 'content_type' azure function
【解决方案2】:

使用下面给出的代码

return HttpResponse(config_data)

对于响应,您可以检查状态

【讨论】:

  • 谢谢,我可以访问数据,但它将是文本形式。我实际上想要一个对象在我的模板中,以便我可以迭代它以获得所需的值。
  • user3327831 您必须发送对象的 JSON、XML 或类似表示形式。
猜你喜欢
  • 2012-09-12
  • 1970-01-01
  • 2016-07-06
  • 2013-08-08
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
相关资源
最近更新 更多