Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - detect mobile device in views

Tags:

django

I am already using a device detection (http://djangosnippets.org/snippets/2228/) in my templates and trying to also make it work in views, so i can redirect to the app store if a user comes from an iPhone.

So I already had:

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, '.')

    # 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 }

And then created a class in tools/middleware.py:

from tools.context_processor import mobile

class detect_device(object):

    def process_request(self, request):
        device = mobile(request)

        request.device = device

Added the following to MIDDLEWARE_CLASSES in the settings.py:

'tools.middleware.detect_device'

And in views.py I created:

def get_link(request):
    if request.device.iphone:
        app_store_link = settings.APP_STORE_LINK
        return HttpResponseRedirect(app_store_link)
    else:
        return HttpResponseRedirect('/')

But I am getting the error:

'dict' object has no attribute 'iphone'

like image 767
Christoffer Avatar asked Nov 12 '12 22:11

Christoffer


1 Answers

IT's a dictionary, not a class.

Complete view:

def get_link(request):
    if 'iphone' in request.device['device']:
        app_store_link = settings.APP_STORE_LINK
        return HttpResponseRedirect(app_store_link)
    else:
        return HttpResponseRedirect('/')
like image 159
santiagobasulto Avatar answered Oct 20 '22 20:10

santiagobasulto