How to detect Browser type in Django?

How can i detect which browser type the client is using. I have a problem where i have to ask people to use different browser (Firefox) instead of IE. How can i get this information.

I know http request has this information (Header). How will i get the navigator.appName from the view.py in the Django framework ?


Solution 1:

You can extract that information from the request object like so:

request.META['HTTP_USER_AGENT']

Solution 2:

There are multiple ways of getting that done.

The easiest way is what @digitaldreamer recommended. That is you can make a meta request for HTTP_USER_AGENT.

request.META['HTTP_USER_AGENT']

But I would also recommend you to take a look at the Django User Agents library.

Install it with pip

pip install pyyaml ua-parser user-agents
pip install django-user-agents

And configure settings.py:

MIDDLEWARE_CLASSES = (
    # other middlewares...
    'django_user_agents.middleware.UserAgentMiddleware',
)

INSTALLED_APPS = (
    # Other apps...
    'django_user_agents',
)

# Cache backend is optional, but recommended to speed up user agent parsing
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

# Name of cache backend to cache user agents. If it not specified default
# cache alias will be used. Set to `None` to disable caching.
USER_AGENTS_CACHE = 'default'

Usage is pretty simple as well.

A user_agent attribute will now be added to request, which you can use in views.py:

def my_view(request):

# Let's assume that the visitor uses an iPhone...
request.user_agent.is_mobile # returns True
request.user_agent.is_tablet # returns False
request.user_agent.is_touch_capable # returns True
request.user_agent.is_pc # returns False
request.user_agent.is_bot # returns False

# Accessing user agent's browser attributes
request.user_agent.browser  # returns Browser(family=u'Mobile Safari', version=(5, 1), version_string='5.1')
request.user_agent.browser.family  # returns 'Mobile Safari'
request.user_agent.browser.version  # returns (5, 1)
request.user_agent.browser.version_string   # returns '5.1'

# Operating System properties
request.user_agent.os  # returns OperatingSystem(family=u'iOS', version=(5, 1), version_string='5.1')
request.user_agent.os.family  # returns 'iOS'
request.user_agent.os.version  # returns (5, 1)
request.user_agent.os.version_string  # returns '5.1'

# Device properties
request.user_agent.device  # returns Device(family='iPhone')
request.user_agent.device.family  # returns 'iPhone'

Solution 3:

You can look into the 'user agent string' and parse out the values.

Here's the relevant docs, specifically on (HTTP_USER_AGENT):

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