[Django]-Listing object with specific tag using django_taggit

4👍

The key thing is to override the get_queryset method, so that the queryset only includes returns entries with the chosen tag. I have made TagListView inherit from HomePageView, so that it includes the same context data – if that’s not important, you could subclass ArchiveIndexView instead.

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')),

Leave a comment