Generating a unique list of Django-Taggit Tags in Wagtail;

拥有回忆 提交于 2019-12-08 02:41:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!