我已经在我的模板中使用了设备检测(http://djangosnippets.org/snippets/2228/),并试图让它在视图中工作,所以如果用户来自 iPhone,我可以重定向到应用商店。
所以我已经有了:
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 }
然后在 tools/middleware.py 中创建了一个类:
from tools.context_processor import mobile
class detect_device(object):
def process_request(self, request):
device = mobile(request)
request.device = device
在 settings.py 的 MIDDLEWARE_CLASSES 中添加了以下内容:
'tools.middleware.detect_device'
在views.py中我创建了:
def get_link(request):
if request.device.iphone:
app_store_link = settings.APP_STORE_LINK
return HttpResponseRedirect(app_store_link)
else:
return HttpResponseRedirect('/')
但我收到错误:
'dict' 对象没有属性 'iphone'