Ejemplo n.º 1
0
def show_articles(request):
    """
    method for getting page with articles
    :param request:
    :return TemplateResponse:

    param request can has tuple with GET parameters:
    :parameter page: show page number; default = 1
    :parameter page_length: show how much articles will be on page; default = 12
    """
    args = {}
    page = 1
    page_length = 12
    if request.GET.get('page'):
        page = int(request.GET.get('page'))
    if request.GET.get('page_length'):
        page_length = int(request.GET.get('page_length'))
    article_query = Article.objects.all().order_by('publication_date').reverse()
    paginator = Paginator(article_query, page_length)
    articles = paginator.page(page)
    paginator.page_lrange = range(1, paginator.num_pages + 1)
    paginator.current_page = page
    args['articles'] = articles
    args['paginator'] = paginator
    return render(request, 'articles.html', args)
Ejemplo n.º 2
0
    def get_queryset_with_paginator(self,
                                    model_or_qset,
                                    base_url=None,
                                    search_query=None,
                                    obj_per_page=OBJECTS_PER_PAGE,
                                    manager='objects',
                                    result_manager='objects',
                                    distinct=False,
                                    annotate=None,
                                    order_non_fields=None):

        if hasattr(model_or_qset, '_meta'):
            model = model_or_qset
        else:
            model = model_or_qset.model

        base_url = base_url or self.request.path

        queryset = self.get_queryset_ids(model_or_qset,
                                         search_query=search_query,
                                         manager=manager,
                                         distinct=distinct,
                                         annotate=annotate,
                                         order_non_fields=order_non_fields)

        paginator = Paginator(queryset, obj_per_page)
        try:

            page = paginator.page(self.page)
        except InvalidPage:
            raise Http404(_('Page %s does not exist.') % self.page)
            # Django that can't throw exceptions other than 404.

        result_qset = getattr(
            model, result_manager).filter(id__in=tuple(page.object_list))

        if annotate:
            result_qset = result_qset.annotate(**annotate)

        if self.extra:
            result_qset = result_qset.extra(**self.extra)

        if self.order:
            result_qset = result_qset.order_by(*self.order)  # 1082

        if order_non_fields:
            result_qset = result_qset.order_by(order_non_fields)

        # XXX
        page.object_list = result_qset

        paginator.current_page = page
        paginator.current_object_list = result_qset

        paginator.base_url = base_url

        return paginator
Ejemplo n.º 3
0
    def get_queryset_with_paginator(
            self, model_or_qset, base_url=None, search_query=None,
            obj_per_page=OBJECTS_PER_PAGE, manager='objects',
            result_manager='objects', distinct=False,
            annotate=None, order_non_fields=None):

        if hasattr(model_or_qset, '_meta'):
            model = model_or_qset
        else:
            model = model_or_qset.model

        base_url = base_url or self.request.path

        queryset = self.get_queryset_ids(
            model_or_qset, search_query=search_query, manager=manager,
            distinct=distinct, annotate=annotate, order_non_fields=order_non_fields)

        paginator = Paginator(queryset, obj_per_page)
        try:

            page = paginator.page(self.page)
        except InvalidPage:
            raise Http404(_('Page %s does not exist.') % self.page)
            # Django that can't throw exceptions other than 404.

        result_qset = getattr(
            model, result_manager).filter(id__in=tuple(page.object_list))

        if annotate:
            result_qset = result_qset.annotate(**annotate)

        if self.extra:
            result_qset = result_qset.extra(**self.extra)

        if self.order:
            result_qset = result_qset.order_by(*self.order)  # 1082

        if order_non_fields:
            result_qset = result_qset.order_by(order_non_fields)

        # XXX
        page.object_list = result_qset

        paginator.current_page = page
        paginator.current_object_list = result_qset

        paginator.base_url = base_url

        return paginator
Ejemplo n.º 4
0
def by_date(request, page=1):
    try:
        page = int(page)
    except (ValueError, TypeError):
        page = 1
    
    news = New.objects.all()
    pager = Paginator(news, 10)
    pager.current_page = page
    
    context = {
        'pager': pager,
        'results': pager.page(page),
    }
    return render_to_response('news/by_date.html', context)
Ejemplo n.º 5
0
def by_source(request, source, page=1):
    try:
        page = int(page)
    except (ValueError, TypeError):
        page = 1
    
    news = New.objects.filter(source_slug=source)
    pager = Paginator(news, 10)
    pager.current_page = page
    
    entry = pager.page(page).object_list[0]
    
    context = {
        'pager': pager,
        'results': pager.page(page),
        'site_name': entry.source_name,
        'site_slug': entry.source_slug,
    }
    return render_to_response('news/by_source.html', context)
Ejemplo n.º 6
0
def any_feedback(request, template):
    try:
        page_num = int(request.GET.get('page', 1))
    except ValueError:
        page_num = 1
    search_args = []
    search_text = request.GET.get('search_text')
    if search_text:
        search_args.append(
            Q(var1__icontains=search_text) | Q(message__icontains=search_text))
    filter_name = request.GET.get('filter_name')
    filter_value = request.GET.get('filter_value')
    if filter_name and filter_value:
        search_args.append(Q(**{'%s__icontains' % filter_name: filter_value}))
    search_args.append(Q(processing_status=defaults.PUBLISHED))
    items = Feedback.objects.filter(*search_args)
    paginator = Paginator(items, defaults.FEEDBACK_PER_PAGE)
    page = paginator.page(page_num)
    paginator.current_page = page
    objects_list = page.object_list
    if template.replace('/', '').split(".")[-1] != 'html':
        template = template.replace('/', '') + '.html'
    return dict(items=objects_list, paginator=paginator, template=template)
Ejemplo n.º 7
0
    def get_queryset_with_paginator(self,
                                    models,
                                    base_url=None,
                                    search_query=None,
                                    obj_per_page=OBJECTS_PER_PAGE,
                                    managers='objects',
                                    distinct=False):
        base_url = base_url or self.request.path

        if isinstance(managers, basestring):
            managers = [managers] * len(models)

        model_qsets = []

        for model, manager in zip(models, managers):
            model_manager = getattr(model, manager)
            model_qset = model_manager.all()
            model_qsets.append(model_qset)

        if type(search_query) is dict:
            querysets = [
                model_qset.filter(**search_query) for model_qset in model_qsets
            ]

        elif type(search_query) is tuple:
            querysets = [
                model_qset.filter(*search_query[0], **search_query[1])
                for model_qset in model_qsets
            ]

        elif callable(search_query):
            querysets = [
                search_query(model_qset) for model_qset in model_qsets
            ]

        elif search_query is not None:
            try:
                querysets = [
                    model_qset.filter(search_query)
                    for model_qset in model_qsets
                ]
            except:
                querysets = [
                    search_query.values_list('id', flat=True)
                    for model_qset in model_qsets
                ]
        else:
            querysets = model_qsets

        if self.order:
            querysets = [
                queryset.order_by(*self.order) for queryset in querysets
            ]

        if distinct:
            querysets = [queryset.distinct() for queryset in querysets]

        paginator = Paginator(MultiQueryset(querysets), obj_per_page)
        try:

            page = paginator.page(self.page)
        except InvalidPage:
            raise Http404(_('Page %s does not exist.') % self.page)
            # Django that can't throw exceptions other than 404.

        # result_qset = getattr(
        #    model, result_manager).filter(
        #        id__in=tuple(page.object_list))

        # if self.order:
        # result_qset = result_qset.order_by(*self.order)  # 1082

        paginator.current_page = page
        paginator.current_object_list = page.object_list
        paginator.base_url = base_url

        return paginator
Ejemplo n.º 8
0
    def _timeline(
            self, request, consumer_types, root, attr_name=None, attr_id=None):
        # Templates are cached in a dict.
        templates = defaultdict(
            lambda: get_template(
                'spicy.history/providers/%s.html' % template_name))

        # TODO custom SQL for consumer.root checking
        consumer_types_list = consumer_types.split(',')
        actions = models.Action.objects.filter(
            show_in_timeline=True,
            consumer_type__model__in=consumer_types_list,
            action_type__in=[0, 1],
            ).order_by('-date_joined')

        if attr_name is not None and attr_id is not None:
            queries = []
            action_ids = []
            for ctype_string in consumer_types_list:
                ctype = ContentType.objects.get(model=ctype_string)
                consumers = getattr(ctype.model_class(), 'objects').all()
                
                action_ids.extend(actions.filter(
                    consumer_type__id=ctype.id,
                    consumer_id__in=consumers.filter(
                        is_public=True,
                        **{attr_name: attr_id}).values_list('id', flat=True)
                    ).values_list('id', flat=True))
                            
            actions = actions.filter(
                pk__in=[aid for aid in action_ids])

        elif len(consumer_types_list) == 1:
            manager = (
                'with_attrs' if consumer_types == 'tag' else 'objects')
            ctype = ContentType.objects.get(model=consumer_types)
            consumers = getattr(ctype.model_class(), manager).all()
            if root:
                queries = []
                key = 'term__slug'
                for i in xrange(defaults.GEOTARGET_TAG_ROOT_DEPTH):
                    key = 'vocabulary__' + key
                    queries.append(Q(**{key: root}))
                consumers = consumers.filter(
                    reduce(operator.or_, queries), is_public=True)

            actions = actions.filter(
                consumer_id__in=[consumer.id for consumer in consumers])
            consumers_dict = dict(
                (consumer.id, consumer) for consumer in consumers)
            for action in actions:
                action.consumer = consumers_dict[action.consumer_id]
        
        providers = []
        for action in actions:
            if action.consumer and action.consumer.check_public():
                if root and hasattr(action.consumer, 'root'):
                    if action.consumer.root is None or (
                            action.consumer.root and
                            action.consumer.root.slug != root):
                        continue

                template_name = action.consumer.get_history_template(
                    action.action_type)
                context = Context({
                    'action': action, 'consumer': action.consumer})
                template = templates[template_name]
                action.rendered_template = template.render(context)
                providers.append(action)

        page = request.GET.get('page', 1)
        paginator = Paginator(providers, sk_defaults.OBJECTS_PER_PAGE)

        try:
            paginator.current_page = paginator.page(page)
        except InvalidPage:
            raise Http404(unicode(_('Page %s does not exist.' % page)))
        #paginator.base_url = reverse(
        #     'service:public:history-timeline', args=[consumer_types, root])

        return dict(
            paginator=paginator, consumer_types=consumer_types, root=root)
Ejemplo n.º 9
0
    def get_queryset_with_paginator(
            self, models, base_url=None, search_query=None,
            obj_per_page=OBJECTS_PER_PAGE, managers='objects', distinct=False):
        base_url = base_url or self.request.path

        if isinstance(managers, basestring):
            managers = [managers] * len(models)

        model_qsets = []

        for model, manager in zip(models, managers):
            model_manager = getattr(model, manager)
            model_qset = model_manager.all()
            model_qsets.append(model_qset)

        if type(search_query) is dict:
            querysets = [
                model_qset.filter(**search_query) for model_qset in
                model_qsets]

        elif type(search_query) is tuple:
            querysets = [
                model_qset.filter(*search_query[0], **search_query[1])
                for model_qset in model_qsets]

        elif callable(search_query):
            querysets = [
                search_query(model_qset) for model_qset in model_qsets]

        elif search_query is not None:
            try:
                querysets = [
                    model_qset.filter(search_query) for model_qset in
                    model_qsets]
            except:
                querysets = [
                    search_query.values_list('id', flat=True)
                    for model_qset in model_qsets]
        else:
            querysets = model_qsets

        if self.order:
            querysets = [
                queryset.order_by(*self.order) for queryset in querysets]

        if distinct:
            querysets = [queryset.distinct() for queryset in querysets]

        paginator = Paginator(
            MultiQueryset(querysets), obj_per_page)
        try:

            page = paginator.page(self.page)
        except InvalidPage:
            raise Http404(_('Page %s does not exist.') % self.page)
            # Django that can't throw exceptions other than 404.

        # result_qset = getattr(
        #    model, result_manager).filter(
        #        id__in=tuple(page.object_list))

        # if self.order:
        # result_qset = result_qset.order_by(*self.order)  # 1082

        paginator.current_page = page
        paginator.current_object_list = page.object_list
        paginator.base_url = base_url

        return paginator
Ejemplo n.º 10
0
    def render(self, context):
        for var in (True, False, None):
            # Not needed in Django 1.5?
            context[unicode(var)] = var
        
        try:
            slug = self.slug.resolve(context)
        except:
            slug = None 
        app = self.app.resolve(context)
        model = self.model.resolve(context)

        try:
            obj_type = ContentType.objects.get(app_label=app, model=model)
            objects = obj_type.model_class().objects.all()
            if not self.show_all:
                objects = objects.filter(
                    is_public=True, pub_date__lte=datetime.now())
        except AttributeError:
            return EmptyModelError(app, model)

        try:
            if slug:
                objects = objects.filter(category__slug=slug)
        except obj_type.model_class().DoesNotExist:
            pass

        def get_vars((k, v)):
            try:
                return k, template.Variable(v).resolve(context)
            except template.VariableDoesNotExist:
                return ()

        if self.sort:
            objects = objects.order_by(*self.sort)

        if self.filter_query:
            objects = objects.filter(
                **dict(filter(
                    None, (get_vars(item) for item in self.filter_query))))

        if self.labels:
            try:
                labels = self.labels.resolve(context)
            except template.VariableDoesNotExist:
                labels = None
            if labels:
                objects = objects.filter(label__text__in=labels.split(','))

        if self.paginate:
            request = context.get('request')
            if request:
                try:
                    page_num = int(request.GET.get('page', 1))
                except ValueError:
                    page_num = 1

            paginator = Paginator(objects, self.num_per_page.resolve(context))
            context['paginator'] = paginator
            page = paginator.page(page_num)
            context['pages'] = page
            if self.show_prev_objects:
                objs = []
                for num in range(1, page_num+1):
                    prev_page_objs = paginator.page(num).object_list
                    objs.extend(prev_page_objs)
                paginator.current_page = page
            else:
                paginator.current_page = page
                objs = page.object_list
        else:
            objs = objects[:self.num_per_page.resolve(context)]

        results = []
        last_obj = len(objs) - 1
        for i, obj in enumerate(objs):
            context[self.object_name] = obj
            context['loop_counter'] = i
            context['last_category'] = i == last_obj
            try:
                result = self.nodelist.render(context)
                results.append(result)
            except Exception:
                pass
        return ''.join(results)