How to detect Browser type in Django?
You can extract that information from the request object like so:
request.META['HTTP_USER_AGENT']
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-agentspip 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 parsingCACHES = { '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 Truerequest.user_agent.is_tablet # returns Falserequest.user_agent.is_touch_capable # returns Truerequest.user_agent.is_pc # returns Falserequest.user_agent.is_bot # returns False# Accessing user agent's browser attributesrequest.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 propertiesrequest.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 propertiesrequest.user_agent.device # returns Device(family='iPhone')request.user_agent.device.family # returns 'iPhone'
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