source: cyclope/core/collections/frontend_views.py @ 192:a8fb72f9ad53

Revision 192:a8fb72f9ad53, 9.5 KB checked in by nicoechaniz <nico@…>, 3 years ago (diff)

fixed CategoryLabeledIconList? view

Line 
1#!/usr/bin/env python
2# -*- coding: UTF-8 -*-
3#
4# Copyright 2010 Código Sur - Nuestra América Asoc. Civil / Fundación Pacificar.
5# All rights reserved.
6#
7# This file is part of Cyclope.
8#
9# Cyclope is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# Cyclope is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
22"""cyclope.frontend_views"""
23
24from django.utils.translation import ugettext_lazy as _
25from django.template import loader, RequestContext
26from django.http import Http404, HttpResponse
27from django.core.paginator import Paginator, InvalidPage, EmptyPage
28
29from cyclope import settings as cyc_settings
30from cyclope.core import frontend
31from cyclope.core.collections.models import Collection, Category
32from cyclope.utils import template_for_request
33
34class CategoryRootItemsList(frontend.FrontendView):
35    """A flat list view of category members.
36    """
37    name='root_items_list'
38    verbose_name=_('list of root items for the selected Category')
39
40    def get_string_response(self, request, content_object=None, *args, **kwargs):
41        category = content_object
42        c = RequestContext(request,
43                           {'categorizations': category.categorizations.all()})
44        t = loader.get_template("collections/category_root_items_list.html")
45        c['host_template'] = 'cyclope/inline_view.html'
46        return t.render(c)
47
48    def get_http_response(self, request, slug=None, *args, **kwargs):
49        category = Category.objects.get(slug=slug)
50        c = RequestContext(request,
51                           {'categorizations': category.categorizations.all()})
52        t = loader.get_template("collections/category_root_items_list.html")
53        c['host_template'] = template_for_request(request)
54        return HttpResponse(t.render(c))
55
56frontend.site.register_view(Category, CategoryRootItemsList())
57
58
59class CategoryTeaserList(frontend.FrontendView):
60    """A teaser list view of category members.
61    """
62    name='teaser_list'
63    verbose_name=_('teaser list of Category members')
64    is_default = True
65    template = "collections/category_teaser_list.html"
66    items_per_page = cyc_settings.CYCLOPE_PAGINATION['TEASER']
67
68    def get_string_response(self, request, content_object=None, *args, **kwargs):
69        category = content_object
70        #TODO(nicoechaniz): this article__date ordering looks bad. categories can hold any baseontent derivative
71        c = RequestContext(request,
72                           {'categorizations': category.categorizations.order_by('article__date'),
73                            'region_view': True,
74                            'category': category})
75        t = loader.get_template(self.template)
76        c['host_template'] = 'cyclope/inline_view.html'
77        return t.render(c)
78
79    def get_http_response(self, request, slug=None, *args, **kwargs):
80        category = Category.objects.get(slug=slug)
81        # TODO(nicoechaniz):this hardcoded order_by es wrong. fix it.
82        categorizations_list = category.categorizations.order_by('article__date')
83
84        paginator = Paginator(categorizations_list, self.items_per_page)
85
86        # Make sure page request is an int. If not, deliver first page.
87        try:
88            page_number = int(request.GET.get('page', '1'))
89        except ValueError:
90            page_number = 1
91
92        # DjangoDocs uses page differently
93        # If page request (9999) is out of range, deliver last page of results.
94        try:
95            page = paginator.page(page_number)
96        except (EmptyPage, InvalidPage):
97            page = paginator.page(paginator.num_pages)
98
99        c = RequestContext(request,
100                           {'categorizations': page.object_list,
101                            'page': page,
102                            'category': category })
103        t = loader.get_template(self.template)
104        c['host_template'] = template_for_request(request)
105        return HttpResponse(t.render(c))
106
107frontend.site.register_view(Category, CategoryTeaserList())
108
109class CategoryLabeledIconList(CategoryTeaserList):
110    """A labeled icon list view of category members.
111    """
112    name='labeled_icon_list'
113    verbose_name=_('Labeled icon list of Category members')
114    template = "collections/category_labeled_icon_list.html"
115    is_default = False
116    items_per_page = cyc_settings.CYCLOPE_PAGINATION['LABELED_ICON']
117
118frontend.site.register_view(Category, CategoryLabeledIconList())
119
120class CategorySimplifiedTeaserList(frontend.FrontendView):
121    """A teaser list view of category members.
122    """
123    name='simplified_teaser_list'
124    verbose_name=_('simplified teaser list of Category members')
125
126    def get_string_response(self, request, content_object=None, *args, **kwargs):
127        category = content_object
128        c = RequestContext(request,
129                           {'categorizations': category.categorizations.all(),
130                            'category': category,
131                            'simplified_view': True})
132        t = loader.get_template("collections/category_teaser_list.html")
133        c['host_template'] = 'cyclope/inline_view.html'
134        return t.render(c)
135
136frontend.site.register_view(Category, CategorySimplifiedTeaserList())
137
138
139class CollectionRootCategoriesTeaserList(frontend.FrontendView):
140    """ A teaser list of the root categories of a collection
141    """
142    name = 'root_categories_teaser_list'
143    verbose_name=_('teaser list of the root Categories of a Collection')
144    is_default = True
145
146    def get_http_response(self, request, slug=None, *args, **kwargs):
147        collection = Collection.objects.get(slug=slug)
148        c = RequestContext(
149            request,
150            {'categories': Category.tree.filter(collection=collection, level=0),
151             'collection': collection })
152        t = loader.get_template("collections/collection_root_categories_teaser_list.html")
153        c['host_template'] = template_for_request(request)
154        return HttpResponse(t.render(c))
155
156frontend.site.register_view(Collection, CollectionRootCategoriesTeaserList())
157
158
159class CollectionCategoriesHierarchy(frontend.FrontendView):
160    """A hierarchical list view of the categories in a collection.
161    """
162    name='categories_hierarchy'
163    verbose_name=_('hierarchical list of Categories in a Collection')
164    target_view = 'teaser_list'
165
166    def get_string_response(self, request, content_object=None, *args, **kwargs):
167
168        collection = content_object
169        categories = Category.tree.filter(collection=collection, level=0)
170        category_list = []
171        for category in categories:
172            category_list.extend(self._get_categories_nested_list(category))
173        c = RequestContext(request, {'categories': category_list,
174                                     'collection_slug': collection.slug})
175        t = loader.get_template("collections/collection_categories_hierarchy.html")
176        c['host_template'] = 'cyclope/inline_view.html'
177        return t.render(c)
178
179    def _get_categories_nested_list(self, base_category, name_field='name'):
180
181        """Creates a nested list to be used with unordered_list template tag
182        """
183        #TODO(nicoechaniz): see if there's a more efficient way to build this recursive template data.
184        #TODO(nicoechaniz): only show categories which have children or content.
185        from django.template import Template, Context
186        link_template = Template(
187            '{% if has_children %}'
188              '<span class="expand_collapse">+</span>\n'
189            '{% endif %}'
190            '{% if has_content %}'
191              '<a href="{% url category-'+self.target_view+' slug %}">'
192                 '<span>{{ name }}</span></a>'
193            '{% else %} {{ name }}'
194            '{% endif %}'
195            )
196        nested_list = []
197        for child in base_category.get_children():
198            if child.get_descendant_count()>0:
199                nested_list.extend(self._get_categories_nested_list(
200                    child, name_field=name_field))
201            else:
202                name = getattr(child, name_field)
203                has_content = child.categorizations.exists()
204                nested_list.append(link_template.render(
205                    Context({'name': name,
206                             'slug': child.slug,
207                             'has_content': has_content,})))
208
209        name = getattr(base_category, name_field)
210        has_content = base_category.categorizations.exists()
211        include = link_template.render(
212            Context({'name': name,
213                     'slug': base_category.slug,
214                     'has_content': has_content,
215                     'has_children': base_category.get_descendant_count()}))
216        return [include, nested_list]
217
218frontend.site.register_view(Collection, CollectionCategoriesHierarchy())
219
220class CollectionCategoriesHierarchyToIconlist(CollectionCategoriesHierarchy):
221    """A hierarchical list view of the categories in a collection that will show a labeled_icon list view of the category that the user selects.
222    """
223    name='categories_hierarchy_to_iconlist'
224    verbose_name=_('hierarchical list of Categories that will show an icon list on click')
225    target_view = 'labeled_icon_list'
226
227frontend.site.register_view(Collection, CollectionCategoriesHierarchyToIconlist())
Note: See TracBrowser for help on using the repository browser.