37

How do I add a response header to a Django response? I have:

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

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

# Alternately using render_to_response
# return render_to_response("template.html", {})
Alasdair
  • 298,606
  • 55
  • 578
  • 516
user984003
  • 28,050
  • 64
  • 189
  • 285

1 Answers1

59

Assign the result of render to a variable, set the header, then return the response.

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

Most of the time, it is simpler to user render than render_to_response. However, if you are using render_to_response, the same approach will work:

response = render_to_response("template.html", {})
response['Cache-Control'] = 'no-cache'
return response
Alasdair
  • 298,606
  • 55
  • 578
  • 516