【问题标题】:I want to show first 2 objects in my django template but it shows me this error我想在我的 django 模板中显示前 2 个对象,但它显示了这个错误
【发布时间】:2018-12-19 03:55:50
【问题描述】:
{% for post in object_list|slice : "2" %}
<div class="w3-container w3-card w3-white w3-round w3-margin"><br>
    <img src="/w3images/avatar5.png" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px">
    <span class="w3-right w3-opacity">{{post.date}}</span>
    <h4>{{ post.author.username }}</h4><br>
    <hr class="w3-clear">
    <p>{{post.text}}</p>
  </div>
{% endfor %}

显示的错误是

'for' 语句应使用格式'for x in y':for post in object_list|slice : "2"

当我删除 slice:2 时,该代码有效。如果我再次添加它会抛出如上的错误。

【问题讨论】:

  • 如果去掉空格怎么办,所以slice:"2"而不是slice : "2"
  • 尝试在切片后添加slice:":2"
  • 毕竟你在这里所做的只是混合两种语法,结果,解析器会感到困惑。
  • 感谢 Willem 和 Manoj 的回答。删除空格使它对我有用!

标签: django for-loop django-templates slice


【解决方案1】:

应该是[注意额外的:]

{% for post in object_list|slice : ":2" %}

docs

【讨论】:

    猜你喜欢
    • 2021-03-10
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2021-11-25
    • 2018-05-09
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多