2010-02-23 62 views
32

我有一个用Django编写的Web应用程序,它有一个特定的页面,我想实现该模板的移动版本(以及稍微不同的逻辑)。我希望能够实现它ALA这个须藤代码:在python视图中检测手机浏览器(不只是iPhone)

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,Android和主流设备...

http_user_agent字符串是否有某种移动标志可以检查?

+0

错字:须藤=伪 – pmont 2014-01-31 15:18:18

回答

19

更新:

我才发现:http://code.google.com/p/minidetector/

这似乎做我想要什么,我现在要去测试。随意告诉我,我错了!

+0

谢谢你的分享是找到。对我而言,那些中间件看起来比我用来实现类似目的的所有本土解决方案更好。 – ayaz 2010-11-11 08:01:34

+2

该项目是否最新?自2010年12月以来,它没有发生过任何变化。我正在使用https://github.com/shelfworthy/minidetector,因为它是积极开发的。不幸的是,作者刚刚告诉我,它不再支持,他一直在删除该github回购,所以我正在寻找替代品。 – 2011-11-28 20:49:05

+0

如果你检查minidector的网络有一些叉是不是过时 - https://github.com/saschwarz/minidetector/network – Alvin 2012-09-13 10:38:20

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> 
+1

许多人遵循这个约定,但我不喜欢它,因为它会迫使开发人员拥有大量的if语句而不是1个。你可以争辩说,完全展示不同的模板不是干的,但我认为分离两者的理智是值得的。 – Mikhail 2013-09-15 02:10:51

7

随时随地minidetecor称为Django的.mobi的叉,它包括关于如何使用它的文档。

https://pypi.python.org/pypi/django-mobi

+0

这似乎是最好的解决方案。 __“分叉描述:我重新组织代码,添加缓存,并在这里和那里做了一些调整。”__ – Druska 2013-04-22 13:13:45

相关问题