![](/img/trans.png)
[英]How to save tag in django to my model using django-taggit
[英]Django/django-taggit — How to access filtered tag name in template
我正在寻找访问我的标签名称的正确语法。
这是我的看法:
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"),
我想到了。 我刚刚在上下文字典中添加了'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 %}
似乎Concert具有tags
的ManyToManyField
,因此,当您执行{{ concerts.0 }}
,您可以访问Concert
实例。 {{ concerts.0.tags }}
,您可以访问许多标签,因为Concert具有许多标签。
因此,如果要显示一个标签,则需要切片一个
{{ concerts.0.tags.0.name }}
或者,如果您想显示与该演唱会相关的所有标签,则可以使用{%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 %}
是只添加一个逗号,
作为标签之间的隔板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.