[Django]-How to add an HTTP header to all Django responses

99👍

Yes, you should have a look at middlewares.

yourapp/middleware.py

class MyMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['X-My-Header'] = "my value"
        return response

yourproject/settings.py

MIDDLEWARE = [
    ...,
    'yourapp.middleware.MyMiddleware',
    ...,
]

3👍

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 

Leave a comment