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?

angelos_lex
  • 1,593
  • 16
  • 24
  • 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](https://docs.djangoproject.com/en/2.2/ref/request-response/#attributes-set-by-middleware) do. – Alasdair Jun 17 '19 at 14:42

1 Answers1

10

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"
Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87
JPG
  • 82,442
  • 19
  • 127
  • 206