Removed that annoying banner ;) Next year, make this an admin option.
[wolnelektury.git] / apps / newtagging / views.py
1 """
2 Tagging related views.
3 """
4 from django.http import Http404
5 from django.utils.translation import ugettext as _
6 from django.views.generic.list_detail import object_list
7
8
9 def tagged_object_list(request, queryset_or_model=None, tag_model=None, tags=None,
10         related_tags=False, related_tag_counts=True, **kwargs):
11     """
12     A thin wrapper around
13     ``django.views.generic.list_detail.object_list`` which creates a
14     ``QuerySet`` containing instances of the given queryset or model
15     tagged with the given tag.
16
17     In addition to the context variables set up by ``object_list``, a
18     ``tag`` context variable will contain the ``Tag`` instance for the
19     tag.
20
21     If ``related_tags`` is ``True``, a ``related_tags`` context variable
22     will contain tags related to the given tag for the given model.
23     Additionally, if ``related_tag_counts`` is ``True``, each related
24     tag will have a ``count`` attribute indicating the number of items
25     which have it in addition to the given tag.
26     """
27     # Check attributes
28     if queryset_or_model is None:
29         raise AttributeError(_('tagged_object_list must be called with a queryset or a model.'))
30     if tag_model is None:
31         raise AttributeError(_('tagged_object_list must be called with a tag model.'))
32     if tags is None:
33         raise AttributeError(_('tagged_object_list must be called with a tag.'))
34
35     tag_instances = tag_model.get_tag_list(tags)
36     if tag_instances is None:
37         raise Http404(_('No tags found matching "%s".') % tags)
38     queryset = tag_model.intermediary_table_model.objects.get_intersection_by_model(queryset_or_model, tag_instances)
39     if not kwargs.has_key('extra_context'):
40         kwargs['extra_context'] = {}
41     kwargs['extra_context']['tags'] = tag_instances
42     if related_tags:
43         kwargs['extra_context']['related_tags'] = \
44             tag_model.objects.related_for_model(tag_instances, queryset_or_model,
45                                           counts=related_tag_counts)
46     return object_list(request, queryset, **kwargs)
47