46

I use a custom http header for URL signature just called "sign", how to get such custom HTTP header value in Django?

Jason Xu
  • 2,903
  • 5
  • 31
  • 54

6 Answers6

83

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']

Slam
  • 8,112
  • 1
  • 36
  • 44
owencm
  • 8,384
  • 6
  • 38
  • 54
17

Finally I found just get it through

request.META('HTTP_{your uppercased header name}')
Jason Xu
  • 2,903
  • 5
  • 31
  • 54
  • 1
    Thanks for the helpful pointer. Besides uppercasing the header name, I had to replace dashes with underscores. So, header name "My-custom-header" is request.META['HTTP_MY_CUSTOM_HEADER'] – Raj Jan 28 '14 at 07:41
  • This code gives the following error `TypeError: 'dict' object is not callable`. Calling `request.META.get('HTTP_{your uppercased header name}')` is the correct way. – justin Feb 02 '21 at 00:00
16

You can add your own custom headers to a response like so: https://docs.djangoproject.com/en/dev/ref/request-response/#setting-headers

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

Or use a decorator to add them to a view: http://djangosnippets.org/snippets/275/

rockingskier
  • 9,066
  • 3
  • 40
  • 49
8

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. :-)

Rohit Khatri
  • 1,980
  • 3
  • 25
  • 45
6

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

jlapoutre
  • 1,767
  • 18
  • 22
3

From the Django documentation:

https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.META

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

Michael van de Waeter
  • 1,473
  • 15
  • 29