6

I want to implement a middleware in django, that will append a header on the request's existing headers, before the get_response(request) function.

Though, when trying like this:

request.headers['CUSTOM_HEADER'] = 'CUSTOM_VALUE'

I get an error: 'HttpHeaders' object does not support item assignment
Also in django's request (WSGIRequest), there is no add_headers function like the python's request module.
Any ideas on how this can be accomplished?

1
  • Depending on your use case, you could set an attribute on the request object itself, e.g. request.CUSTOM = 'CUSTOM_VALUE. This is what several Django middlewares do. Commented Jun 17, 2019 at 14:42

1 Answer 1

14

Create a simple middleware as below, and put the path in the MIDDLEWARE settings.

from django.utils.deprecation import MiddlewareMixin


class CustomHeaderMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.META['HTTP_CUSTOM_HEADER'] = "CUSTOM VALUE"
Sign up to request clarification or add additional context in comments.

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.