Cisplatin Cisplatin - 1 month ago 11
HTTP Question

How to add an HTTP header to all Django responses

I'd like to add a few headers to all responses that my Django website returns. Is there a way to do this (besides adding a wrapper to the

render
function)?

Answer

Yes, you should have a look at middlewares.

Django >= 1.10

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',
    ...,
]

Django <= 1.9

yourapp/middleware.py

class MyMiddleware:
    def process_response(self, request, response):
        response['X-My-Header'] = "my value"
        return response

yourproject/settings.py

MIDDLEWARE_CLASSES = [
    ...,
    'yourapp.middleware.MyMiddleware',
    ...,
]
Comments