Preparing for Django 1.10
[wolnelektury.git] / src / newtagging / views.py
1 # -*- coding: utf-8 -*-
2 """
3 Tagging related views.
4 """
5 from django.http import Http404
6 from django.utils.translation import ugettext as _
7 from django.views.generic import ListView
8
9
10 def tagged_object_list(request, queryset_or_model, tag_model, tags, related_tags=False,
11                        related_tag_counts=True, **kwargs):
12     """
13     A thin wrapper around
14     ``django.views.generic.list_detail.object_list`` which creates a
15     ``QuerySet`` containing instances of the given queryset or model
16     tagged with the given tag.
17
18     In addition to the context variables set up by ``object_list``, a
19     ``tag`` context variable will contain the ``Tag`` instance for the
20     tag.
21
22     If ``related_tags`` is ``True``, a ``related_tags`` context variable
23     will contain tags related to the given tag for the given model.
24     Additionally, if ``related_tag_counts`` is ``True``, each related
25     tag will have a ``count`` attribute indicating the number of items
26     which have it in addition to the given tag.
27     """
28
29     tag_instances = tag_model.get_tag_list(tags)
30     if tag_instances is None:
31         raise Http404(_('No tags found matching "%s".') % tags)
32     queryset = tag_model.intermediary_table_model.objects.get_by_model(queryset_or_model, tag_instances)
33     if 'extra_context' not in kwargs:
34         kwargs['extra_context'] = {}
35     kwargs['extra_context']['tags'] = tag_instances
36     if related_tags:
37         kwargs['extra_context']['related_tags'] = \
38             tag_model.objects.related_for_model(tag_instances, queryset_or_model, counts=related_tag_counts)
39     return ListView.as_view(queryset=queryset)(request, **kwargs)