如何在Django视图中获取请求头中的xyzId和abcData?
Hey there! The issue you're facing comes down to how Django processes HTTP request headers under the hood. Let me break it down and show you the correct way to access those custom headers.
Why request.META['abcData'] Throws a KeyError
Django automatically transforms incoming request headers to a standardized format:
- All characters are converted to uppercase
- Prefixes the header name with
HTTP_ - Replaces any camelCase capitalization or hyphens (
-) with underscores (_)
So your custom headers get renamed like this:
xyzId→HTTP_XYZIDabcData→HTTP_ABCDATA
Correct Way to Access the Headers
Use these transformed keys with request.META. For safer access (to avoid KeyError if the header is missing), use the get() method instead of direct key lookup:
In a Function-Based View:
from django.http import JsonResponse def your_api_view(request): if request.method == 'POST': # Get custom headers (returns None if header doesn't exist) xyz_id = request.META.get('HTTP_XYZID') abc_data = request.META.get('HTTP_ABCDATA') # If you're certain the headers will always be present, you can use direct lookup: # xyz_id = request.META['HTTP_XYZID'] # abc_data = request.META['HTTP_ABCDATA'] # Process your data here return JsonResponse({ 'xyzId': xyz_id, 'abcData': abc_data })
In a Class-Based View (e.g., DRF APIView):
from rest_framework.views import APIView from rest_framework.response import Response class YourAPIView(APIView): def post(self, request): xyz_id = request.META.get('HTTP_XYZID') abc_data = request.META.get('HTTP_ABCDATA') return Response({ 'xyzId': xyz_id, 'abcData': abc_data })
Pro Tip
Using get() is recommended because it gracefully handles cases where the header might be missing (returns None instead of crashing with a KeyError). You can even set a default value if needed:
abc_data = request.META.get('HTTP_ABCDATA', 'default_value')
内容的提问来源于stack exchange,提问作者Mr Singh

