Django — Get browser and OS info from the HTTP requests

Photo by Firmbee.com on Unsplash

This blog post focuses on finding various information about the nature of the browser and os from which the HTTP requests are made. The following information can be obtained from the requests.

  1. If the device is a mobile/PC
  2. Browser name
  3. Browser version
  4. OS of the computer or mobile
  5. OS version
  6. Device name

Let us get started. There are actually two ways to obtain this information.

  1. The 'HTTP_USER_AGENT' header data from the request object
  2. Using a django-user-agents library.

Let us get started.

In Django, each type of HTTP request is received at the backend via a request object. This request object will have various data such as the user, request body, header data, and much more.

The META object will have all the necessary header data. The browser type can be obtained from the header using this META object simply as

This will return us something like this.

To be honest we cannot get the accurate browser/browser version using this method. Of course, you can go ahead find the pattern, and parse the data from this string. But if you do not have time for that I would suggest the second method.

This is a sample gist that will get the above result, print it, and also will return a response to the GET method.

This library will do all the parsing work for you and pretty much will give you only the data you need.

Install this library by running the following command.

After that add it to the INSTALLED_APPS in the settings.py file.

Also, add UserAgentMiddleware in settings.py:

Once this middleware is added, now all our requests will have an additional attribute called user_agent, which can be accessed like this.

Now we can get the following information from the request.user_agent object.

We can get the device type as PC/mobile/tablet/touch_capable from the user_agent attribute as

I am making the request from my PC so only this is_pc attribute returns true whereas all other attributes return false.

We can get the name of our browser and browser version like this.

I made the requests from my safari web browser. This is the screenshot showing my browser info.

browser version

You can see that the version is pretty much accurate. If you want to troubleshoot issues occurring only in some particular versions of a browser alone, this will come in handy.

We can also get information about the operating system from this user_agent attribute.

I am also adding a screenshot of my OS and its version.

os version info

You can see that this is also extremely accurate.

I am also adding a sample gist. This is how you would use it in a views file.

Hope this article is helpful. If you need to know more about this library, have a look at their documentation.

Happy coding!