【问题标题】:Django/django-taggit -- How to access filtered tag name in templateDjango/django-taggit -- 如何在模板中访问过滤后的标签名称
【发布时间】:2018-05-22 17:34:20
【问题描述】:

我正在寻找正确的语法来访问我的标签名称。

这是我的看法:

def tag_filter(request, tag):
    now = datetime.datetime.now()
    concerts = Concert.objects.filter(tags__name__in=[tag])\
                              .filter(date__gte=now).order_by('date')
    return render(request, 'concerts/calendar.html', {'concerts': concerts})

这确实得到了我想要的数据。我想在模板的标题中显示标签的名称,但这是我遇到障碍的地方。我正在尝试这个:

  {% elif request.resolver_match.url_name == "tag_filter" %}
  <h1>Upcoming Events with "{{ concerts.0.tags.name }}" Tag</h1>
  {% endif %}

但是{{ concerts.0.tags.name }} 什么也没返回。我已经尝试了一些变化,但到目前为止还没有。有任何想法吗?谢谢!

编辑添加我的urlconf,以防万一:

url(r'^tag/(?P<tag>[\w-]+)/$', views.tag_filter, name="tag_filter"),

【问题讨论】:

  • 你能在渲染视图之前print(concerts) 向我们展示输出吗?也许查询集是空的
  • 如果我进入 shell 并运行上面的查询,然后运行print concerts[0].tags.all(),我得到&lt;QuerySet [&lt;Tag: rock&gt;, &lt;Tag: electronica&gt;]&gt;。但我真的只是想获得与我的网址中相同的标签。

标签: django django-taggit


【解决方案1】:

Concert 似乎有一个ManyToManyFieldtags,所以当你这样做时:{{ concerts.0 }},你可以访问一个Concert 实例。 {{ concerts.0.tags }} 在那里您可以访问许多标签,因为 Concert 有很多标签。

所以如果要显示一个标签,就需要切片一个

{{ concerts.0.tags.0.name }}

或者如果您想显示与该 Concert 相关的所有标签,您可以使用 {% for loop %}

<h1>Upcoming Events with "{% for tag in concerts.0.tags.all %}{{ tag }}{% if not forloop.last %}, {% endif %}{% endfor %}" Tag</h1>

{% if not forloop.last %}, {% endif %}只是在标签之间添加一个逗号,作为分隔符。

【讨论】:

    【解决方案2】:

    我想通了。我刚刚将 'tag': 标记添加到我的上下文字典中,然后我可以轻松地在模板中调用 {{ tag }}。希望这对将来的某人有所帮助。 :)

    查看:

    def tag_filter(request, tag):
        now = datetime.datetime.now()
        concerts = Concert.objects.filter(tags__name__in=[tag])\
                                  .filter(date__gte=now).order_by('date')
        return render(request, 'concerts/calendar.html', {'concerts': concerts,
                                                          'tag': tag})
    

    模板:

      {% elif request.resolver_match.url_name == "tag_filter" %}
      <h1>Upcoming Events with "{{ tag }}" Tag</h1>
      {% endif %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-05
      • 2019-09-27
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 2020-02-16
      相关资源
      最近更新 更多