source: cyclope/core/collections/frontend_views.py @ 234:df6be40513bc

Revision 234:df6be40513bc, 9.7 KB checked in by Diego Mascialino <dmascialino@…>, 3 years ago (diff)

Fixed order and pagination for category views

H: Enter commit message. Lines beginning with 'HG:' are removed.

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.core.paginator import Paginator, InvalidPage, EmptyPage
27
28from cyclope import settings as cyc_settings
29from cyclope.core import frontend
30from cyclope.core.collections.models import Collection, Category
31from cyclope.utils import template_for_request
32
33class CategoryRootItemsList(frontend.FrontendView):
34    """A flat list view of the root members for a Category.
35    """
36    name='root_items_list'
37    verbose_name=_('list of root items for the selected Category')
38
39    is_content_view = True
40    is_region_view = True
41
42    def get_response(self, request, host_template, content_object):
43        category = content_object
44        categorizations_list = category.categorizations.all()
45        template = "collections/category_root_items_list.html"
46        c = RequestContext(request,
47                           {'categorizations': categorizations_list })
48        t = loader.get_template(template)
49        c['host_template'] = host_template
50        return t.render(c)
51
52frontend.site.register_view(Category, CategoryRootItemsList)
53
54class CategoryDefaultList(frontend.FrontendView):
55    name = 'default'
56    verbose_name = _('default view for the Collection')
57    is_default = True
58    is_content_view = True
59
60    def get_response(self, request, host_template, content_object):
61        category = content_object
62        if category.collection.default_list_view not in ["", self.name]:
63            view_name = category.collection.default_list_view
64            view = frontend.site.get_view(content_object.__class__, view_name)
65        else:
66            view = frontend.site.get_view(content_object.__class__, 'teaser_list')
67        return view.get_response(request, host_template, content_object)
68
69frontend.site.register_view(Category, CategoryDefaultList)
70
71
72class CategoryTeaserList(frontend.FrontendView):
73    """A teaser list view of Category members.
74    """
75    name = 'teaser_list'
76    verbose_name = _('teaser list of Category members')
77    items_per_page = cyc_settings.CYCLOPE_PAGINATION['TEASER']
78    is_content_view = True
79    is_region_view = True
80
81    template = "collections/category_teaser_list.html"
82
83    def get_response(self, request, host_template, content_object):
84        category = content_object
85        categorizations_list = category.categorizations.all()
86
87        # TODO(diegoM): ¡¡¡ No escala !!!
88        categorizations_list = sorted(categorizations_list,
89                                      key=lambda c: c.object_modification_date,
90                                      reverse=True)
91
92
93        paginator = Paginator(categorizations_list, self.items_per_page)
94
95        # Make sure page request is an int. If not, deliver first page.
96        try:
97            page_number = int(request.GET.get('page', '1'))
98        except ValueError:
99            page_number = 1
100
101        # DjangoDocs uses page differently
102        # If page request (9999) is out of range, deliver last page of results.
103        try:
104            page = paginator.page(page_number)
105        except (EmptyPage, InvalidPage):
106            page = paginator.page(paginator.num_pages)
107
108        c = RequestContext(request,
109                           {'categorizations': page.object_list,
110                            'page': page,
111                            'category': category })
112        t = loader.get_template(self.template)
113        c['host_template'] = host_template
114        return t.render(c)
115
116frontend.site.register_view(Category, CategoryTeaserList)
117
118
119class CategoryLabeledIconList(CategoryTeaserList):
120    """A labeled icon list view of Category members.
121    """
122    name='labeled_icon_list'
123    verbose_name=_('Labeled icon list of Category members')
124    is_default = False
125    items_per_page = cyc_settings.CYCLOPE_PAGINATION['LABELED_ICON']
126    template = "collections/category_labeled_icon_list.html"
127
128frontend.site.register_view(Category, CategoryLabeledIconList)
129
130
131class CategorySimplifiedTeaserList(frontend.FrontendView):
132    """A teaser list view of category members.
133    """
134    name='simplified_teaser_list'
135    verbose_name=_('simplified teaser list of Category members')
136    is_region_view = True
137
138    def get_response(self, request, host_template, content_object):
139        category = content_object
140        categorizations_list = category.categorizations.all()
141
142        template = "collections/category_teaser_list.html"
143        c = RequestContext(request,
144                           {'category': category,
145                            'categorizations': categorizations_list,
146#                            'region_view': True,
147                            'simplified_view': True,
148                            })
149        t = loader.get_template(template)
150        c['host_template'] = host_template
151        return t.render(c)
152
153frontend.site.register_view(Category, CategorySimplifiedTeaserList)
154
155
156class CollectionRootCategoriesTeaserList(frontend.FrontendView):
157    """ A teaser list of the root Categories of a Collection
158    """
159    name = 'root_categories_teaser_list'
160    verbose_name=_('teaser list of the root Categories of a Collection')
161    is_default = True
162    is_content_view = True
163    template = "collections/collection_root_categories_teaser_list.html"
164
165    def get_response(self, request, host_template, content_object):
166        collection = content_object
167        c = RequestContext(
168            request,
169            {'categories': Category.tree.filter(collection=collection, level=0),
170             'collection': collection })
171        t = loader.get_template(self.template)
172        c['host_template'] = host_template
173        return t.render(c)
174
175frontend.site.register_view(Collection, CollectionRootCategoriesTeaserList)
176
177
178class CollectionCategoriesHierarchy(frontend.FrontendView):
179    """A hierarchical list view of the Categories in a Collection.
180    """
181    name='categories_hierarchy'
182    verbose_name=_('hierarchical list of Categories in a Collection')
183    target_view = 'default'
184    is_content_view = True
185    is_region_view = True
186
187    def get_response(self, request, host_template, content_object):
188        collection = content_object
189        categories = Category.tree.filter(collection=collection, level=0)
190        category_list = []
191        for category in categories:
192            category_list.extend(self._get_categories_nested_list(category))
193        c = RequestContext(request, {'categories': category_list,
194                                     'collection_slug': collection.slug})
195        template = "collections/collection_categories_hierarchy.html"
196        t = loader.get_template(template)
197        c['host_template'] = host_template
198        return t.render(c)
199
200    def _get_categories_nested_list(self, base_category, name_field='name'):
201
202        """Creates a nested list to be used with unordered_list template tag
203        """
204        #TODO(nicoechaniz): see if there's a more efficient way to build this recursive template data.
205        #TODO(nicoechaniz): only show categories which have children or content.
206        from django.template import Template, Context
207        link_template = Template(
208            '{% if has_children %}'
209              '<span class="expand_collapse">+</span>\n'
210            '{% endif %}'
211            '{% if has_content %}'
212              '<a href="{% url category-'+self.target_view+' slug %}">'
213                 '<span>{{ name }}</span></a>'
214            '{% else %} {{ name }}'
215            '{% endif %}'
216            )
217        nested_list = []
218        for child in base_category.get_children():
219            if child.get_descendant_count()>0:
220                nested_list.extend(self._get_categories_nested_list(
221                    child, name_field=name_field))
222            else:
223                name = getattr(child, name_field)
224                has_content = child.categorizations.exists()
225                nested_list.append(link_template.render(
226                    Context({'name': name,
227                             'slug': child.slug,
228                             'has_content': has_content,})))
229
230        name = getattr(base_category, name_field)
231        has_content = base_category.categorizations.exists()
232        include = link_template.render(
233            Context({'name': name,
234                     'slug': base_category.slug,
235                     'has_content': has_content,
236                     'has_children': base_category.get_descendant_count()}))
237        if nested_list:
238            return [include, nested_list]
239        else:
240            return [include]
241
242frontend.site.register_view(Collection, CollectionCategoriesHierarchy)
243
244class CollectionCategoriesHierarchyToIconlist(CollectionCategoriesHierarchy):
245    """A hierarchical list view of the Categories in a Collection that will show a labeled_icon list view of the category that the user makes a selection.
246    """
247    name='categories_hierarchy_to_iconlist'
248    verbose_name=_('hierarchical list of Categories that will show an icon list on click')
249    target_view = 'labeled_icon_list'
250
251frontend.site.register_view(Collection, CollectionCategoriesHierarchyToIconlist)
Note: See TracBrowser for help on using the repository browser.