首页 > 解决方案 > 如何使用 django-taggit 获取按标签过滤的文章列表?

问题描述

我想按标签列出文章以在标题中包含标签的标题,在列表中包含文章的标题。我的 view.py 看起来像这样:

from taggit.models import TaggedItem

class ArticlesByTagsList(ListView):

    template_name = 'articles/articles_by_tags.html'
    context_object_name = 'articles_list'

    def get_queryset(self):
        return TaggedItem.objects.filter(tag=self.kwargs['tag'])

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['tags_list'] = Tag.objects.all()
        return context

我的articles_by_tags.html 模板如下所示:

{% block content %}

    <h1>Список публикаций {{ articles_list.item }}</h1>

    {% for item in articles_list %}
        <h2>{{ item }}</h2>
    {% endfor %}


{% endblock %}

我最终得到以下输出:ArticlesByTagsList.as_view() 结果

我怎么解决这个问题?

标签: djangodjango-modelsdjango-viewsdjango-templatesdjango-taggit

解决方案


推荐阅读