Login

Mobile Device Middleware

Author:
stephen_mcd
Posted:
May 22, 2010
Language:
Python
Version:
1.2
Tags:
middleware template mobile
Score:
2 (after 2 ratings)

Middleware class that checks the user agent against a known list of strings found in mobile devices, and if matched it then tries to determine the name of the template being rendered based on the convention of having every view use a keyword arg called "template". It then adds "mobile" to the template name and if the mobile template exists, it will override the "template" arg for the view with the mobile template name.

 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
MOBILE_USERAGENTS = ("2.0 MMP","240x320","400X240","AvantGo","BlackBerry",
    "Blazer","Cellphone","Danger","DoCoMo","Elaine/3.0","EudoraWeb",
    "Googlebot-Mobile","hiptop","IEMobile","KYOCERA/WX310K","LG/U990",
    "MIDP-2.","MMEF20","MOT-V","NetFront","Newt","Nintendo Wii","Nitro",
    "Nokia","Opera Mini","Palm","PlayStation Portable","portalmmm","Proxinet",
    "ProxiNet","SHARP-TQ-GX10","SHG-i900","Small","SonyEricsson","Symbian OS",
    "SymbianOS","TS21i-10","UP.Browser","UP.Link","webOS","Windows CE",
    "WinWAP","YahooSeeker/M1A1-R2D2","iPhone","iPod","Android",
    "BlackBerry9530","LG-TU915 Obigo","LGE VX","webOS","Nokia5800")

class MobileTemplate(object):
    """
    If a mobile user agent is detected, inspect the default args for the view 
    func, and if a template name is found assume it is the template arg and 
    attempt to load a mobile template based on the original template name.
    """

    def process_view(self, request, view_func, view_args, view_kwargs):
        if any(ua for ua in MOBILE_USERAGENTS if ua in 
            request.META["HTTP_USER_AGENT"]):
            template = view_kwargs.get("template")
            if template is None:
                for default in view_func.func_defaults:
                    if str(default).endswith(".html"):
                        template = default
            if template is not None:
                template = template.rsplit(".html", 1)[0] + ".mobile.html"
                try:
                    get_template(template)
                except TemplateDoesNotExist:
                    pass
                else:
                    view_kwargs["template"] = template
                    return view_func(request, *view_args, **view_kwargs)
        return None

More like this

  1. Detect iPhone & Switch Template via render_to_response by bryanhelmig 5 years ago
  2. Mobilize your Django site by stevena0 6 years, 1 month ago
  3. A templatetag to insert the output of another view (or local URL) by jamesgpearce 5 years, 11 months ago
  4. Mobile browser detection middleware by pavl 5 years ago
  5. Simple Mobile Support by bahoo 4 years, 7 months ago

Comments

Please login first before commenting.