Adding a Request Slug to a Generic Class View

Created on Oct. 17, 2012, 11:21 p.m. by Hevok & updated by Hevok on May 2, 2013, 5:23 p.m.

Data entries belonging to a certain tag can be gathered in class-based generic view via a slug in the request: ::

class TagDetail(ListView):
    """Get all entries for a tag."""
    template_name = 'detail_tag.html'

    def get_context_data(self, *args, **kwargs):
        ctx = super(TagDetail, self).get_context_data(*args, **kwargs)
        ctx['slug'] = self.kwargs['slug'] # or Tag.objects.get(slug=...)
        return ctx

   def get_queryset(self):
       tags = get_list_or_404(Entry, tags__slug=self.kwargs['slug'], displayed=True)
       return tags

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(TagDetail, self).dispatch(*args, **kwargs)

Tags: django, view, slugs
Categories: Tutorial
Parent: Web Framework

Update entry (Admin) | See changes

Comment on This Data Unit