问题
I am trying to add a list of category tags in the sidebar of my Wagtail blog index page. The code below does work, but unfortunately it iterates through the posts and lists all the tags as individual tags, which I ultimately end up with duplicate tags. I built my blog from the Wagtail demo and since it doesn't use Views like I am used to, I am not sure where to add .distinct('tags').
Template
{% for b in blogs %}
{% for tag in b.tags.all %}
<li><a href="{% pageurl b.blog_index %}?tag={{ tag }}" class="btn btn-primary btn-xs"> <i class="glyphicon glyphicon-tag"></i> {{ tag }}<span>{{ tag }}</span></a>
{% if not forloop.last %} {% endif %}
</li>
{% endfor %}
{% endfor %}
回答1:
Any logic that would normally go in a view function, can go in the page model's get_context
method:
from django.contrib.contenttypes.models import ContentType
from taggit.models import Tag
class BlogIndex(Page):
# ...
def get_context(self, request):
context = super(BlogIndex, self).get_context(request)
blog_content_type = ContentType.objects.get_for_model(BlogPage)
context['tags'] = Tag.objects.filter(
taggit_taggeditem_items__content_type=blog_content_type
)
return context
(the tag-fetching code here is adapted from some internal Wagtail code.)
来源:https://stackoverflow.com/questions/38061564/generating-a-unique-list-of-django-taggit-tags-in-wagtail