使用django_taggit列出具有特定标记的对象

时间:2011-12-17 20:59:47

标签: django django-views

我有一个使用django_taggit的博客应用。我的HomePageView子类ArchiveIndexView效果很好。

现在,我想要使用以下链接:http://mysite.com/tag/yellow,我想使用ArchiveIndexView泛型类,并传入一个过滤tag_slug的修改过的查询集。我想这样做是因为我想使用与主页相同的模板。

我的urls.py

url(r'^$', HomePageView.as_view(paginate_by=5, date_field='pub_date',template_name='homepage.html'),
    ),

url(r'^tag/(?P<tag_slug>[-\w]+)/$', 'tag_view'), # I know this is wrong

我的views.py

class HomePageView(ArchiveIndexView):
"""Extends the detail view to add Events to the context"""
model = Entry

def get_context_data(self, **kwargs):
    context = super(HomePageView, self).get_context_data(**kwargs)
    context['events'] = Event.objects.filter(end_time__gte=datetime.datetime.now()
                                             ).order_by('start_time')[:5]
    context['comments'] = Comment.objects.filter(allow=True).order_by('created').reverse()[:4]
    return context

我意识到我已经迷失在这里,并希望找到一些帮助,找出如何创建一个新的类TagViewPage(),通过过滤tag_slug来修改查询集。

1 个答案:

答案 0 :(得分:4)

关键是要覆盖get_queryset方法,以便查询集只包含带有所选标记的返回条目。我已将TagListViewHomePageView继承,因此它包含相同的上下文数据 - 如果这不重要,则可以替代ArchiveIndexView

class TagListView(HomePageView):
    """
    Archive view for a given tag
    """

    # It probably makes more sense to set date_field here than in the url config
    # Ideally, set it in the parent HomePageView class instead of here.
    date_field = 'pub_date'

    def get_queryset(self):
        """
        Only include entries tagged with the selected tag
        """
        return Entry.objects.filter(tags__name=self.kwargs['tag_slug'])

    def get_context_data(self, **kwargs):
        """
        Include the tag in the context
        """
        context_data = super(TagListView, self).get_context_data(self, **kwargs)
        context_data['tag'] = get_object_or_404(Tag, slug=self.kwargs['tag_slug'])
        return context_data

# urls.py
url(r'^tag/(?P<tag_slug>[-\w]+)/$', TagListView.as_view(paginate_by=5, template_name='homepage.html')),