【问题标题】:Why isn't mobile detection enabled working in my Django template?为什么在我的 Django 模板中没有启用移动检测?
【发布时间】:2019-07-30 22:59:54
【问题描述】:

我正在使用 Django 和 Python 3.7。我想在移动浏览器上显示一些稍微不同的表格数据,所以我将表格视图模板格式化如下:

{% if request.user_agent.is_mobile %}
    <td align="center"><a href="{{ articlestat.article.mobile_path }}" target="_blank">{{ articlestat.hits|floatformat:"0" }}</a></td>
{% else %}
    <td align="center"><h2><a href="{{ articlestat.article.path }}" target="_blank">{{ articlestat.hits|floatformat:"0" }}</a></h2></td>
{% endif %}

但是,在部署并重新启动我的服务器后,在移动浏览器上查看它仍然会显示非移动分支。我还需要做些什么来激活移动检测吗?我的手机是 Android LG,如果需要,可以在 Chrome 浏览器上查看。

编辑:我正在使用“django-user-agents”扩展程序,在这里可以找到——https://github.com/selwin/django-user_agents。事实上,我对任何可以准确检测移动浏览器的解决方案持开放态度,这恰好是 Google 上出现的第一个解决方案。

【问题讨论】:

  • 您是否也在其他移动设备上尝试过?或者只是通过设置不同的用户代理在您的浏览器上进行测试? -> 如果您的移动代码仍未显示,请检查request-object 和(如果存在)request.user_agent 的内容,也许这会给您更多信息,例如也许你只是忘记了中间件之类的。

标签: python django python-3.x templates mobile


【解决方案1】:

你试过Template Filters吗?您可以通过执行以下操作来使用它们:

{% load user_agents %}

{% if request|is_mobile %}
    Mobile device stuff...
{% endif %}

否则,您应该尝试在模板中输入 {{ request|is_mobile }} 并查看它的输出。

您的另一个选择是使用 CSS 来定位 divs,并根据屏幕大小隐藏/显示它们。这并不准确,但它是高度可定制的。示例:

html

<td class="td-desktop" align="center"><h2><a href="{{ articlestat.article.path }}" target="_blank">{{ articlestat.hits|floatformat:"0" }}</a></h2></td>
<td class="td-mobile" align="center"><a href="{{ articlestat.article.mobile_path }}" target="_blank">{{ articlestat.hits|floatformat:"0" }}</a></td>

css

.td-mobile {
    display: none;
}
@media (max-width:768px)  {
    .td-desktop {
        display: none;
    }
    .td-mobile {
        display: block;
    }
}

【讨论】:

  • 我需要安装什么额外的库才能让它工作?当我添加“{% load user_agents %}”行时出现错误,“'user_agents' 不是注册的标签库”,即使我有“django-user-agents==0.3.2”作为我项目的一部分。
  • 它是同一个包的一部分,这意味着它没有正确安装。尝试运行“pip install pyyaml ua-parser user-agents”,然后将“django-user-agents”添加到您的 INSTALLED_APPS。另外,请确保添加此处指定的所有内容:github.com/selwin/django-user_agents/blob/master/README.rst
  • 所以我使用 Pip 安装了所有模块,但是在将“django-user-agents”添加到我安装的应用程序后,我收到错误消息“ModuleNotFoundError: No module named 'django-user-agents'”当我重新启动我的应用程序并尝试访问相关页面时。
  • 哦,嘿,它实际上是“django_user_agents”,现在我没有得到错误。打算再进行一些测试,但这看起来真的很好。
  • @Dave 我的错字很糟糕!告诉我进展如何
猜你喜欢
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多