使用Django和Python 3检测移动设备 [英] Detect mobile devices with Django and Python 3
问题描述
我正在努力寻找一种简单的方法来检测请求是否来自我的Django视图中的移动设备.
I am struggling to find an easy way to detect if the request comes from a mobile device in my Django views.
我正在尝试实现类似这样的东西:
I am trying to implement something like this:
#views.py
def myfunction(request):
...
if request.mobile:
is_mobile = True
else:
is_mobile = False
context = {
... ,
'is_mobile': is_mobile,
}
return render(request, 'mytemplate.html', context)
在mytemplate.html
中:
{% if is_mobile %}
show something
{% else %}
show something else
{% endif %}
Everywhere I checked (for instance here or here), minidetector is recommended. I have installed different versions: pip install minidetector
, pip install minidetector2
, as well as directly a couple of github repositories, but none of them are compatible with Python 3.
所以这是我的问题:是否有与Python 3兼容的minidetector的任何版本/叉子?如果没有,那还有什么选择?
So here my question: Is there any version/fork of minidetector that is compatible with Python 3? If not, what are the alternatives?
推荐答案
Django用户代理程序包与Python 3兼容.
Django User Agents package is compatible with Python 3.
按照上面提供的链接中的安装说明进行操作,然后可以按以下方式使用它:
Follow the installation instructions in the link provided above and then you can use it as follows:
def my_view(request):
# Let's assume that the visitor uses an iPhone...
request.user_agent.is_mobile # returns True
request.user_agent.is_tablet # returns False
request.user_agent.is_touch_capable # returns True
request.user_agent.is_pc # returns False
request.user_agent.is_bot # returns False
# Accessing user agent's browser attributes
request.user_agent.browser # returns Browser(family=u'Mobile Safari', version=(5, 1), version_string='5.1')
request.user_agent.browser.family # returns 'Mobile Safari'
request.user_agent.browser.version # returns (5, 1)
request.user_agent.browser.version_string # returns '5.1'
# Operating System properties
request.user_agent.os # returns OperatingSystem(family=u'iOS', version=(5, 1), version_string='5.1')
request.user_agent.os.family # returns 'iOS'
request.user_agent.os.version # returns (5, 1)
request.user_agent.os.version_string # returns '5.1'
# Device properties
request.user_agent.device # returns Device(family='iPhone')
request.user_agent.device.family # returns 'iPhone'
模板中的用法如下:
{% if request.user_agent.is_mobile %}
Do stuff here...
{% endif %}
但是,请注意,中间件类在Django 1.10中已更改.因此,如果您使用的是Django 1.10 +,则必须按照此 GitHub问题跟踪器页面.
However, note that the middleware class has changed in Django 1.10. So if you are using Django 1.10 +, you will have to modify the middleware class definition in this Package as given in this GitHub issue tracker page.
这篇关于使用Django和Python 3检测移动设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!