1

So I'm trying to add a custom header to every request in my Django app, I followed this question, and my setup looks like this:

middleware.py:

from django.utils.deprecation import MiddlewareMixin


class ReverseProxyLocalMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.META['User-Id'] = 1

settings.py:

...
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'myapp.middleware.ReverseProxyLocalMiddleware',
]

views.py:

class UserViewSet(
    viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin
):
    queryset = models.User.objects.all()
    serializer_class = serializers.UserSerializer

    def get_queryset(self):
        return models.User.objects.active(dt=timezone.now())

    def list(self, request):
        user_id = request.META['User-Id']
        ...

However, anytime I try and access the new header in a test I get:

    def list(self, request):
>       user_id = request.META['User-Id']
E       KeyError: 'User-Id'

Does anyone have any idea what I'm doing wrong?

7
  • Why are trying to put in META? Commented Dec 13, 2019 at 10:39
  • It was my (I'm guessing poor) understanding that this is how you added custom headers - is there another way I'm meant to do it? Commented Dec 13, 2019 at 10:40
  • I tried your example and it's working. Which views are you using? Commented Dec 13, 2019 at 10:45
  • Added the Django view. Commented Dec 13, 2019 at 10:48
  • Are you mixing drf viewsets and Django mixins? Commented Dec 13, 2019 at 10:56

1 Answer 1

3

Turns out Django drops the header if it's not in the HTTP_*_* format, so the middleware must look like:

from django.utils.deprecation import MiddlewareMixin


class ReverseProxyLocalMiddleware(MiddlewareMixin):
    def process_request(self, request, user_id=1):
        request.META['HTTP_USER_ID'] = user_id
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.