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'
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('/')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With