Django: how to add http header to responses in a convenient way?

Question:

I know we can use HttpResponseInstance['headername'] = 'headervalue' to add header to http response. But in this way, I have to rewrite all the generic view I am using, which makes much more work.

Is there a convenient way to add header to responses, like a callback for responses, or a url decorator?

Asked By: dspjm

||

Answers:

You can write a middleware class and implement the method process_response.

Answered By: Eugene Primako

You should use a middleware class. Check out this thread.

Django 1.10 and above __init__ and __call__ should be implement. process_response is deprecated.

Answered By: Józsa Csongor

Add some custom headers when returning JsonResponse.

from django.http import JsonResponse

data = {'key','value'} # some data

response = JsonResponse(data,status=200)

response['Retry-after'] = 345 # seconds 
response['custom-header'] = 'some value'

return response 

Here is a function you can run that can replace "render" so that it includes the response headers assignments without needing to repeat the value assignments to the different response headers. This is probably useful if you don’t want to repeat your code and you want to apply the changes to some, but not all views. Below is specifically a function that makes sure the rendering doesn’t cache:

def render_cacheless(action, path, context):
    response = render(action, path, context)
    response["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response["Pragma"] = "no-cache"
    response["Expires"] = "0"

    return response

def home(request):
    return render_cacheless(request, "/path/to/home.html", None)
Answered By: dnals
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.