Simple Mobile Support

 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. Detect iPhone & Switch Template via render_to_response by bryanhelmig 3 years, 11 months ago
  2. Mobilize your Django site by stevena0 5 years ago
  3. Mobile browser detection middleware by pavl 3 years, 12 months ago
  4. Digg-like pagination by SmileyChris 4 years, 11 months ago
  5. Page numbers with ... like in Digg by Ciantic 5 years 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

#

(Forgotten your password?)