Code layout change.
[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=None, tag_model=None, tags=None,
11         related_tags=False, 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     # Check attributes
29     if queryset_or_model is None:
30         raise AttributeError(_('tagged_object_list must be called with a queryset or a model.'))
31     if tag_model is None:
32         raise AttributeError(_('tagged_object_list must be called with a tag model.'))
33     if tags is None:
34         raise AttributeError(_('tagged_object_list must be called with a tag.'))
35
36     tag_instances = tag_model.get_tag_list(tags)
37     if tag_instances is None:
38         raise Http404(_('No tags found matching "%s".') % tags)
39     queryset = tag_model.intermediary_table_model.objects.get_by_model(queryset_or_model, tag_instances)
40     if not kwargs.has_key('extra_context'):
41         kwargs['extra_context'] = {}
42     kwargs['extra_context']['tags'] = tag_instances
43     if related_tags:
44         kwargs['extra_context']['related_tags'] = \
45             tag_model.objects.related_for_model(tag_instances, queryset_or_model,
46                                           counts=related_tag_counts)
47     return ListView.as_view(queryset=queryset)(request, **kwargs)
48