6

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?

4 Answers 4

8

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1

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.

Comments

0

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.