在Python视图中检测移动浏览器(不仅限于iPhone)
我有一个用Django写的网页应用,里面有一个特定的页面,我想为它做一个手机版本的模板(还有一些稍微不同的逻辑)。我希望能按照这个伪代码来实现:
def(myView)
do some stuff
if user-is-on-a-mobile-device:
do some stuff
return (my mobile template)
else:
do some stuff
return (my normal template)
我时间不多,而且我刚开始学习编程 :) 我发现了一个看起来很强大的插件,叫做bloom,可以用来获取手机设备的信息 - http://code.google.com/p/django-bloom/wiki/BloomDevice。不过它似乎通过JSON请求获取了很多我不需要的设备信息,这让我觉得有点低效。
有没有人能推荐一个更简单的方法?我的设备检测不需要做到100%准确,只需要识别iPhone、iPod、安卓和一些主流设备就可以了……
http_user_agent字符串里有没有什么可以用来检查手机的标志?
3 个回答
8
可以去找一个叫做django-mobi的minidetecor的分支,它里面有关于如何使用它的说明文档。
15
最佳做法是使用 minidetector 来给请求添加额外的信息,然后利用 Django 自带的请求上下文把这些信息传递到你的模板中,像这样。
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view_on_mobile_and_desktop(request)
.....
render_to_response('regular_template.html',
{'my vars to template':vars},
context_instance=RequestContext(request))
然后在你的模板中,你就可以引入一些内容,比如:
<html>
<head>
{% block head %}
<title>blah</title>
{% if request.mobile %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css">
{% else %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css">
{% endif %}
</head>
<body>
<div id="navigation">
{% include "_navigation.html" %}
</div>
{% if not request.mobile %}
<div id="sidebar">
<p> sidebar content not fit for mobile </p>
</div>
{% endif %>
<div id="content">
<article>
{% if not request.mobile %}
<aside>
<p> aside content </p>
</aside>
{% endif %}
<p> article content </p>
</aricle>
</div>
</body>
</html>
20