Login

Simple Mobile Support

Author:
bahoo
Posted:
October 7, 2010
Language:
Python
Version:
1.2
Tags:
mobile context_processors
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. Detect iPhone & Switch Template via render_to_response by bryanhelmig 4 years, 9 months ago
  2. Mobilize your Django site by stevena0 5 years, 10 months ago
  3. Mobile browser detection middleware by pavl 4 years, 10 months ago
  4. Digg-like pagination by SmileyChris 5 years, 9 months ago
  5. Page numbers with ... like in Digg by Ciantic 5 years, 10 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.