Login

Simple Mobile Support

Author:
bahoo
Posted:
October 7, 2010
Language:
Python
Version:
1.2
Score:
2 (after 2 ratings)

For those interested in making a mobile site geared toward the higher end devices, and wanting a little leverage over device-specific quirks.

These are the big players in the U.S. market, but of course, add your own User-Agents to match your audience's popular browsers.

Usage:

 <html class="{{ device.classes }}">

You can also leverage template logic:

 {% if device.iphone %}
      <p>You are browsing on
           {% if device.iphone = "iphone4" %} iPhone 4
           {% else %} an iPhone pre-version 4{% endif %}
      </p>
 {% endif %}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
## dump this into <project>/context_processors.py, then add '<project>.context_processors.mobile' to TEMPLATE_CONTEXT_PROCESSORS in settings.py
## defaults are not listed; see http://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors to keep those intact.

import re

def mobile(request):

	device = {}

	ua = request.META.get('HTTP_USER_AGENT', '').lower()
	
	if ua.find("iphone") > 0:
		device['iphone'] = "iphone" + re.search("iphone os (\d)", ua).groups(0)[0]
		
	if ua.find("ipad") > 0:
		device['ipad'] = "ipad"
		
	if ua.find("android") > 0:
		device['android'] = "android" + re.search("android (\d\.\d)", ua).groups(0)[0].translate(None, '.')
		
	if ua.find("blackberry") > 0:
		device['blackberry'] = "blackberry"
		
	if ua.find("windows phone os 7") > 0:
		device['winphone7'] = "winphone7"
		
	if ua.find("iemobile") > 0:
		device['winmo'] = "winmo"
		
	if not device:			# either desktop, or something we don't care about.
		device['baseline'] = "baseline"
	
	# spits out device names for CSS targeting, to be applied to <html> or <body>.
	device['classes'] = " ".join(v for (k,v) in device.items())
	
	return {'device': device }

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

chriska (on December 3, 2012):

Very dangerous to have a search without an if or similar statement as in: device['iphone'] = "iphone" + re.search("iphone os (\d)", ua).groups(0)[0]. This made my webapp crash because the HTTP_USER_AGENT was not written exactly how the search was set up

#

Please login first before commenting.