在Django上检测手机,平板电脑或桌面

时间:2012-02-02 20:34:51

标签: django mobile

Im Junior django dev。

我需要检测到3种devicetabletmobiledesktop

我在github上找到了检测到的移动设备的脚本,但我如何检测移动设备,平板电脑和桌面?

谢谢!

5 个答案:

答案 0 :(得分:33)

根据您之前使用的移动检测中间件,我建议如下:

选择Python port of MobileESP (source code here)(感谢Mariusz Miesiak推荐)并将其放入项目基础中名为mobileesp的文件夹中(其中{{ 1}}是。抛出一个空白的manage.py文件,以便Python将其视为一个包。

继续在该目录中创建一个新文件__init__.py,并填写:

middleware.py

最后,请确保在import re from mobileesp import mdetect class MobileDetectionMiddleware(object): """ Useful middleware to detect if the user is on a mobile device. """ def process_request(self, request): is_mobile = False is_tablet = False is_phone = False user_agent = request.META.get("HTTP_USER_AGENT") http_accept = request.META.get("HTTP_ACCEPT") if user_agent and http_accept: agent = mdetect.UAgentInfo(userAgent=user_agent, httpAccept=http_accept) is_tablet = agent.detectTierTablet() is_phone = agent.detectTierIphone() is_mobile = is_tablet or is_phone or agent.detectMobileQuick() request.is_mobile = is_mobile request.is_tablet = is_tablet request.is_phone = is_phone 中的'mobileesp.middleware.MobileDetectionMiddleware',中加入您的设置文件。

在您的视图中(或您拥有请求对象的任何地方),您可以检查MIDDLEWARE_CLASSES(对于任何现代智能手机),is_phone(对于现代平板电脑)或{{ 1}}(对于任何移动设备)。

答案 1 :(得分:5)

看看MobileESP。它最近被移植到Python for Django Web应用程序框架。它可以检测各种类别和层级的设备(包括手机,平板电脑)。

答案 2 :(得分:1)

如果您想要一些快速而简单的解决方案,您可以尝试使用handset detection's javascript来创建简单的重定向规则。

答案 3 :(得分:0)

我正在寻找类似这样的东西,我偶然发现django-mobile正是这样做的。 (我知道这个问题很老了,发布它的人可能是现在的高级Django开发者,但也许这可以帮助人们寻找这些日子。)

答案 4 :(得分:0)

使用django-user_agents

from django_user_agents.utils import get_user_agent

def my_view(request):
    user_agent = get_user_agent(request)
    if user_agent.is_mobile:
        # identified as a mobile phone (iPhone, Android phones, Blackberry, Windows Phone devices etc)
    if user_agent.is_tablet:
        # identified as a tablet device (iPad, Kindle Fire, Nexus 7 etc)
    if user_agent.is_pc:
        # identified to be running a traditional "desktop" OS (Windows, OS X, Linux)

它在引擎盖下使用user_agents