Django:使用render或render_to_response时添加响应头

时间:2013-02-19 11:15:30

标签: django httpresponse

如何为Django响应添加响应头?我有:

response = HttpResponse()
response['Cache-Control'] = 'no-cache'

return render(request, "template.html", {}) 

# Alternately using render_to_response
# return render_to_response("template.html", {})

1 个答案:

答案 0 :(得分:37)

render的结果分配给变量,设置标题,然后返回响应。

response = render(request, "template.html", {})
response['Cache-Control'] = 'no-cache'
return response

大多数情况下,用户renderrender_to_response更简单。但是,如果您使用render_to_response,则相同的方法将起作用:

response = render_to_response("template.html", {})
response['Cache-Control'] = 'no-cache'
return response