I'm looking for the right syntax to access my tag name.
Here's my view:
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})
This is indeed getting the data I want. I'd like to display the name of the tag in the header of my template, but this is where I'm running into a snag. I'm trying this:
{% elif request.resolver_match.url_name == "tag_filter" %}
<h1>Upcoming Events with "{{ concerts.0.tags.name }}" Tag</h1>
{% endif %}
But {{ concerts.0.tags.name }}
is returning nothing. I've tried a few variations but nothing so far. Any ideas? Thank you!
Editing to add my urlconf
, just in case that's relevant:
url(r'^tag/(?P<tag>[\w-]+)/$', views.tag_filter, name="tag_filter"),
I figured it out. I just added the 'tag': tag, to my context dictionary, then I can easily call {{ tag }} in the template. Hope this helps someone in the future. :)
View:
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})
Template:
{% elif request.resolver_match.url_name == "tag_filter" %}
<h1>Upcoming Events with "{{ tag }}" Tag</h1>
{% endif %}
It seems that Concert has a ManyToManyField
to tags
, so when you do: {{ concerts.0 }}
, you have access to a Concert
instance. {{ concerts.0.tags }}
and there you have access to many tags as Concert has Many Tags.
So if you want to display one tag, you need to slice one
{{ concerts.0.tags.0.name }}
Or if you want to display all the tags related to that Concert, you can use {% 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 %}
is only to add a comma ,
as a separator between tags.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.