How to Get Header from Request in Django?

Hi Guys,
In this tutorial, you'll learn how to get HTTP headers from a request in Django using simple and effective methods. If you're wondering how to fetch all request headers in Django or specifically retrieve headers like Authorization
or User-Agent
, this guide provides clear examples for Django 3 and above.
This article also answers the common question — "How can I read headers in a Django view or template?" You'll also learn how Django handles headers case-insensitively, which makes it easier to work with any header format.
Let’s dive into the code example below:
Example:In this step, we will get all header parameters from the request. This includes User-Agent
, Authorization
, and any custom headers sent with the request.
>>> 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
You can also access request headers inside Django templates using dot notation with underscores instead of hyphens. Here's how to get the User-Agent
header:
{{ request.headers.user_agent }}
This is especially useful when you want to conditionally render content based on the user's device or browser.
Frequently Asked Questions (FAQ)
How do I get all headers in Django?
You can access all request headers using request.headers
in Django views. It returns a dictionary-like object that lets you read any header, such as request.headers['User-Agent']
.
Is request.headers case-sensitive in Django?
No, Django handles headers in a case-insensitive manner. request.headers['User-Agent']
and request.headers['user-agent']
will return the same result.
Can I use headers inside Django templates?
Yes, in Django templates you can access headers using dot notation. Replace hyphens with underscores. Example: {{ request.headers.user_agent }}
.
What version of Django supports request.headers?
The request.headers
attribute was introduced in Django 2.2 and is available in all later versions including Django 3.x and Django 4.x.
I hope this detailed guide on Django request headers helps you build more responsive and intelligent backend logic. Let me know if you want a working Django project example!