Custom HTTP Header in Django

ID : 131321

viewed : 9

Tags : djangodjango

Top 5 Answer for Custom HTTP Header in Django

vote vote


Go ahead and use:

request.META.get('HTTP_{your uppercased header name}') 

Note in Django you write the header name in capitals with underscores instead of dashes, but in the request on the client you must write it using dashes instead of underscores (production web servers will strip out custom headers with underscores in them for security reasons).

So, a custom header My-Custom-Header is accessed request.META['HTTP_MY_CUSTOM_HEADER']

vote vote


Finally I found just get it through

request.META('HTTP_{your uppercased header name}') 
vote vote


You can add your own custom headers to a response like so:

>>> response = HttpResponse() >>> response['Cache-Control'] = 'no-cache' >>> del response['Cache-Control'] 

Or use a decorator to add them to a view:

vote vote


I was trying to access the header with the above answers, using this code:

request.META.get('HTTP_{your uppercased header name}') 

But It didn't work for me, and then I realized that the custom header should not contain underscore so I changed the underscore with dash and boom, everything started working. Hope this will help people like me. :-)

vote vote


As of Django 2.2 you can use the HttpRequest.headers dictionary which provides case-insensitive dictionary of request headers, like such:

my_header = request.headers.get('x-my-custom-header') 

See django.http.HttpRequest.headers

Top 3 video Explaining Custom HTTP Header in Django