How to Get Header from Request in Django?

Published On: 09/08/2022 | Category: Django


Hi Guys,

Today, I would like to show you django get request headers. if you have question about how can i get all the request headers in django then I will give simple example with solution. This tutorial will give you simple example of django get authorization header. This article goes in detailed on django add header to request.

In this tuts the name of each header is stylized with title-casing (e.g. User-Agent) when it’s displayed. you can access headers case-insensitively:

You can use these examples with django3 (django 3) version.

let's see below simple example with output:

Example:

In this step, get headers all params from request if you have question about how can i get all the request headers in django.

>>> request.headers
{'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36', ...}

>>> 'User-Agent' in request.headers
True
>>> 'user-agent' in request.headers
True

>>> request.headers['User-Agent']
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
>>> request.headers['user-agent']
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'

>>> request.headers.get('User-Agent')
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
>>> request.headers.get('user-agent')
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'  
Get Django Templates

For use in, for example, Django templates, headers can also be looked up using underscores in place of hyphens:

{{ request.headers.user_agent }}

I Hope It will help you....