Python django.core.paginator.Paginator() Examples

The following are 30 code examples of django.core.paginator.Paginator(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.paginator , or try the search function .
Example #1
Source File: views.py    From monasca-ui with Apache License 2.0 7 votes vote down vote up
def get_data(self):
        page_offset = self.request.GET.get('page_offset')
        results = []
        if page_offset is None:
            page_offset = 0
        limit = utils.get_page_size(self.request)
        try:
            results = api.monitor.alarmdef_list(self.request, page_offset, limit)
            paginator = Paginator(results, limit)
            results = paginator.page(1)
        except EmptyPage:
            results = paginator.page(paginator.num_pages)
        except Exception as ex:
            LOG.exception(str(ex))
            messages.error(self.request, _("Could not retrieve alarm definitions"))

        return results 
Example #2
Source File: views.py    From ran-django-template with GNU General Public License v3.0 7 votes vote down vote up
def search_tag(request, tag):
    posts = Article.objects.filter(tags__name__contains=tag)
    paginator = Paginator(posts, settings.PAGE_NUM)  # 每页显示数量
    try:
        page = request.GET.get('page')  # 获取URL中page参数的值
        post_list = paginator.page(page)
    except PageNotAnInteger:
        post_list = paginator.page(1)
    except EmptyPage:
        post_list = paginator.page(paginator.num_pages)
    return render(request, 'tag.html', {
        'post_list': post_list,
        'category_list': categories,
        'tag': tag,
        'months': months
        }
    ) 
Example #3
Source File: views.py    From WF-website with GNU Affero General Public License v3.0 7 votes vote down vote up
def search(request):
    search_query = request.GET.get('query', None)
    page = request.GET.get('page', 1)

    # Search
    if search_query:
        search_results = Page.objects.live().search(search_query)
        query = Query.get(search_query)

        # Record hit
        query.add_hit()
    else:
        search_results = Page.objects.none()

    # Pagination
    paginator = Paginator(search_results, 10)
    try:
        search_results = paginator.page(page)
    except PageNotAnInteger:
        search_results = paginator.page(1)
    except EmptyPage:
        search_results = paginator.page(paginator.num_pages)

    return render(request, 'search/search.html', {
        'search_query': search_query,
        'search_results': search_results,
    }) 
Example #4
Source File: models.py    From WF-website with GNU Affero General Public License v3.0 7 votes vote down vote up
def get_paginated_memorials(self, filtered_memorials, request):
        items_per_page = 10

        paginator = Paginator(filtered_memorials, items_per_page)

        memorials_page = request.GET.get("page")

        try:
            paginated_memorials = paginator.page(memorials_page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            paginated_memorials = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            paginated_memorials = paginator.page(paginator.num_pages)

        return paginated_memorials 
Example #5
Source File: models.py    From WF-website with GNU Affero General Public License v3.0 7 votes vote down vote up
def get_context(self, request, *args, **kwargs):
        context = super().get_context(request)

        upcoming_events = Event.objects.all().filter(
            Q(date__gt=date.today())).order_by('date')

        # Show three archive issues per page
        paginator = Paginator(upcoming_events, 3)

        upcoming_events_page = request.GET.get("page")

        try:
            paginated_events = paginator.page(upcoming_events_page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            paginated_events = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            paginated_events = paginator.page(paginator.num_pages)

        context["events"] = paginated_events

        return context 
Example #6
Source File: index.py    From BikeMaps with MIT License 7 votes vote down vote up
def index(request):
	POSTS_PER_PAGE = 5
	
	if request.user.is_superuser:
		post_list = Post.objects.all().order_by('-post_date')
	else:
		#post_list = Post.objects.filter(published=True).order_by('-post_date')
		post_list = get_Posts_By_Language_Code(request.LANGUAGE_CODE)

	paginator = Paginator(post_list, POSTS_PER_PAGE)

	page = request.GET.get('page')
	try:
		posts = paginator.page(page)
	except PageNotAnInteger:
		# If page is not an integer, deliver first page.
		posts = paginator.page(1)
	except EmptyPage:
		# If page is out of range, deliver last page of results.
		posts = paginator.page(paginator.num_pages)

	return render(request, 'blogApp/index.html', {'posts': posts}) 
Example #7
Source File: views.py    From ran-django-template with GNU General Public License v3.0 7 votes vote down vote up
def search_category(request, id):
    posts = Article.objects.filter(category_id=str(id))
    category = categories.get(id=str(id))
    paginator = Paginator(posts, settings.PAGE_NUM)  # 每页显示数量
    try:
        page = request.GET.get('page')  # 获取URL中page参数的值
        post_list = paginator.page(page)
    except PageNotAnInteger:
        post_list = paginator.page(1)
    except EmptyPage:
        post_list = paginator.page(paginator.num_pages)
    return render(request, 'category.html',
                  {'post_list': post_list,
                   'category_list': categories,
                   'category': category,
                   'months': months
                  }
    ) 
Example #8
Source File: utils.py    From Servo with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def paginate(queryset, page, count=10):
    """
    Shortcut for paginating a queryset
    """
    paginator = Paginator(queryset, count)

    try:
        results = paginator.page(page)
    except PageNotAnInteger:
        results = paginator.page(1)
    except EmptyPage:
        results = paginator.page(paginator.num_pages)

    return results 
Example #9
Source File: views.py    From FIR with GNU General Public License v3.0 7 votes vote down vote up
def dashboard(request):
    bls = BusinessLine.authorization.for_user(request.user, 'incidents.view_incidents')
    bl_filter = Q(business_line__in=bls) | Q(business_line__isnull=True)
    todos = TodoItem.objects.filter(incident__isnull=False, done=False).filter(bl_filter)
    todos = todos.select_related('incident', 'category')
    todos = todos.order_by('-incident__date')

    page = request.GET.get('page', 1)
    todos_per_page = request.user.profile.incident_number
    p = Paginator(todos, todos_per_page)

    try:
        todos = p.page(page)
    except (PageNotAnInteger, EmptyPage):
        todos = p.page(1)

    return render(request, 'fir_todos/dashboard.html', {'todos': todos}) 
Example #10
Source File: tools.py    From dj-diabetes with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def page_it(data, record_per_page, page=''):
    """
        return the data of the current page
    """
    paginator = Paginator(data, record_per_page)
    try:
        data = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        data = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999),
        # deliver last page of results.
        data = paginator.page(paginator.num_pages)

    return data 
Example #11
Source File: views.py    From dart with Apache License 2.0 7 votes vote down vote up
def get_context_data(self, **kwargs):
        logger.debug('GET: ListMissionView')
        context = super(ListMissionView, self).get_context_data(**kwargs)
        missions = Mission.objects.all()
        paginator = Paginator(missions, 10)
        page = self.request.GET.get('page')
        try:
            show_missions = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            show_missions = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            show_missions = paginator.page(paginator.num_pages)
        context['missions'] = show_missions
        return context 
Example #12
Source File: tests.py    From django-simple-pagination with MIT License 6 votes vote down vote up
def test_page_list(self):
        request = HttpRequest()
        paginator = Paginator(['john', 'paul', 'george', 'ringo'], 3)
        page = paginator.page(1)
        page.number = lambda: None
        setattr(page, 'number', 2)
        setattr(page, 'paginator', paginator)
        page_list = PageList(request=request, page=page, querystring_key="page")
        page_list = PageList(request=request, page=page, querystring_key="page", default_number=1)
        page_list._endless_page(number=1)
        page_list._endless_page(number=3)
        self.assertTrue(page_list[1])
        page_list.next()
        self.assertTrue(page_list)
        si = ShowItems(request=request, page=page, querystring_key="page")
        self.assertTrue(si) 
Example #13
Source File: tests.py    From django-simple-pagination with MIT License 6 votes vote down vote up
def test_page_list(self):
        request = HttpRequest()
        paginator = Paginator(['john', 'paul', 'george', 'ringo'], 3)
        page = paginator.page(1)
        page.number = lambda: None
        setattr(page, 'number', 2)
        setattr(page, 'paginator', paginator)
        page_list = PageList(request=request, page=page, querystring_key="page")
        page_list = PageList(request=request, page=page, querystring_key="page", default_number=1)
        page_list._endless_page(number=1)
        page_list._endless_page(number=3)
        self.assertTrue(page_list[1])
        page_list.next()
        self.assertTrue(page_list)
        si = ShowItems(request=request, page=page, querystring_key="page")
        self.assertTrue(si) 
Example #14
Source File: views.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def get(self, request):
        all_messages = UserMessage.objects.filter(user=request.user.id)

        # 用户进入个人中心消息页面,清空未读消息记录
        all_unread_messages = UserMessage.objects.filter(user=request.user.id, has_read=False)
        for unread_message in all_unread_messages:
            unread_message.has_read = True
            unread_message.save()
        # 对课程机构进行分页
        # 尝试获取前台get请求传递过来的page参数
        # 如果是不合法的配置参数默认返回第一页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 这里指从allorg中取五个出来,每页显示5个
        p = Paginator(all_messages, 4)
        messages = p.page(page)
        return render(request, "usercenter-message.html", {
            "messages": messages
        })


# 首页view 
Example #15
Source File: models.py    From WF-website with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_paginated_archive_issues(self, archive_issues, request):
        items_per_page = 9

        paginator = Paginator(archive_issues, items_per_page)

        archive_issues_page = request.GET.get("page")

        try:
            paginated_archive_issues = paginator.page(archive_issues_page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            paginated_archive_issues = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            paginated_archive_issues = paginator.page(paginator.num_pages)

        return paginated_archive_issues 
Example #16
Source File: views.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def user_profile(request, user_name):
    try:
        user = PytitionUser.objects.get(user__username=user_name)
    except PytitionUser.DoesNotExist:
        raise Http404(_("not found"))

    petitions = user.petition_set.filter(published=True).order_by('-id')
    paginator = Paginator(petitions, settings.PAGINATOR_COUNT)
    page = request.GET.get('page')
    petitions = paginator.get_page(page)

    return render(
        request,
        'petition/user_profile.html',
        {'user': user, 'petitions': petitions}
    )


# /org/<slug:orgslugname>/leave_org
# User is leaving the organisation 
Example #17
Source File: views.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def search(request):
    q = request.GET.get('q', '')
    if q != "":
        petitions = Petition.objects.filter(Q(title__icontains=q) | Q(text__icontains=q)).filter(published=True)[:15]
        orgs = Organization.objects.filter(name__icontains=q)
    else:
        petitions = Petition.objects.filter(published=True).order_by('-id')
        paginator = Paginator(petitions, settings.PAGINATOR_COUNT)
        page = request.GET.get('page')
        petitions = paginator.get_page(page)
        orgs = []
    return render(
        request, 'petition/search.html',
        {
            'petitions': petitions,
            'orgs': orgs,
            'q': q
        }
    ) 
Example #18
Source File: pagination_tags.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self, context):
        key = self.queryset_var.var
        value = self.queryset_var.resolve(context)
        if isinstance(self.paginate_by, int):
            paginate_by = self.paginate_by
        else:
            paginate_by = self.paginate_by.resolve(context)
        paginator = Paginator(value, paginate_by, self.orphans)
        try:
            page_obj = paginator.page(context['request'].page)
        except InvalidPage:
            if INVALID_PAGE_RAISES_404:
                raise Http404('Invalid page requested.  If DEBUG were set to ' +
                    'False, an HTTP 404 page would have been shown instead.')
            context[key] = []
            context['invalid_page'] = True
            return ''
        if self.context_var is not None:
            context[self.context_var] = page_obj.object_list
        else:
            context[key] = page_obj.object_list
        context['paginator'] = paginator
        context['page_obj'] = page_obj
        return '' 
Example #19
Source File: pagination_tags.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self, context):
        key = self.queryset_var.var
        value = self.queryset_var.resolve(context)
        if isinstance(self.paginate_by, int):
            paginate_by = self.paginate_by
        else:
            paginate_by = self.paginate_by.resolve(context)
        paginator = Paginator(value, paginate_by, self.orphans)
        try:
            page_obj = paginator.page(context['request'].page)
        except InvalidPage:
            if INVALID_PAGE_RAISES_404:
                raise Http404('Invalid page requested.  If DEBUG were set to ' +
                    'False, an HTTP 404 page would have been shown instead.')
            context[key] = []
            context['invalid_page'] = True
            return ''
        if self.context_var is not None:
            context[self.context_var] = page_obj.object_list
        else:
            context[key] = page_obj.object_list
        context['paginator'] = paginator
        context['page_obj'] = page_obj
        return '' 
Example #20
Source File: views.py    From dart with Apache License 2.0 6 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(ListMissionTestsSupportingDataView, self).get_context_data(**kwargs)
        testdata = self.get_queryset()
        paginator = Paginator(testdata, 10)
        page = self.request.GET.get('page')
        try:
            show_data = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            show_data = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            show_data = paginator.page(paginator.num_pages)
        context['show_data'] = show_data
        context['this_mission'] = Mission.objects.get(id=self.kwargs['mission'])
        context['this_test'] = TestDetail.objects.get(id=self.kwargs['test_detail'])
        return context 
Example #21
Source File: pagination_tags.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self, context):
        key = self.queryset_var.var
        value = self.queryset_var.resolve(context)
        if isinstance(self.paginate_by, int):
            paginate_by = self.paginate_by
        else:
            paginate_by = self.paginate_by.resolve(context)
        paginator = Paginator(value, paginate_by, self.orphans)
        try:
            page_obj = paginator.page(context['request'].page)
        except InvalidPage:
            if INVALID_PAGE_RAISES_404:
                raise Http404('Invalid page requested.  If DEBUG were set to ' +
                    'False, an HTTP 404 page would have been shown instead.')
            context[key] = []
            context['invalid_page'] = True
            return ''
        if self.context_var is not None:
            context[self.context_var] = page_obj.object_list
        else:
            context[key] = page_obj.object_list
        context['paginator'] = paginator
        context['page_obj'] = page_obj
        return '' 
Example #22
Source File: views.py    From ran-django-template with GNU General Public License v3.0 6 votes vote down vote up
def archives(request, year, month):
    posts = Article.objects.filter(pub_time__year=year, pub_time__month=month).order_by('-pub_time')
    paginator = Paginator(posts, settings.PAGE_NUM)  # 每页显示数量
    try:
        page = request.GET.get('page')  # 获取URL中page参数的值
        post_list = paginator.page(page)
    except PageNotAnInteger:
        post_list = paginator.page(1)
    except EmptyPage:
        post_list = paginator.page(paginator.num_pages)
    return render(request, 'archive.html', {
        'post_list': post_list,
        'category_list': categories,
        'months': months,
        'year_month': year+'.'+month
        }
    ) 
Example #23
Source File: util.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def make_paginator(request, object_list, per_page=10, orphans=3):
    """Return a paginator for object_list from request."""
    paginator = Paginator(object_list, per_page=per_page, orphans=orphans)
    page = request.GET.get('page')
    try:
        objects = paginator.page(page)
    except PageNotAnInteger:
        # if page is not an integer, deliver first page.
        objects = paginator.page(1)
    except EmptyPage:
        # if page is out of range (e.g. 9999), deliver last page of results.
        objects = paginator.page(paginator.num_pages)
    return objects 
Example #24
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def discussion_index(request, course_slug):
    """
    Index page to view all discussion topics
    """
    course, view = _get_course_and_view(request, course_slug)
    if view is None:
        # course is an HttpResponse in this case
        return course
    topics = DiscussionTopic.objects.filter(offering=course).order_by('-pinned', '-last_activity_at')
    activity.update_last_viewed(_get_member(request.user.username, view, course_slug))
    paginator = Paginator(topics, 10)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        topics = paginator.page(page)
    except (EmptyPage, InvalidPage):
        topics = paginator.page(paginator.num_pages)
    context = {'course': course, 'topics': topics, 'view': view, 'paginator': paginator, 'page': page}
    return render(request, 'discuss/index.html', context) 
Example #25
Source File: test_layout.py    From django-rangepaginator with MIT License 5 votes vote down vote up
def test_calculate_range_1(page_num, expected):
    objects = ['foo'] * 50
    paginator = Paginator(objects, 1)
    page = paginator.page(page_num)

    result = calculate_pages(
        page.number, paginator.num_pages, distance=1, edge=1)
    assert expected == result 
Example #26
Source File: views.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def incident_display(request, filter, incident_view=True, paginated=True):
    (order_by, order_param, asc) = incidents_order(request)

    permissions = 'incidents.view_incidents'

    if order_param == 'last_action':
        incident_list = Incident.authorization.for_user(request.user, permissions).filter(filter).annotate(
            Max('comments__date')).order_by(order_by)
    else:
        pre_list = Incident.authorization.for_user(request.user, permissions)
        incident_list = pre_list.filter(filter).order_by(order_by)

    if paginated:
        page = request.GET.get('page', 1)
        incidents_per_page = request.user.profile.incident_number
        p = Paginator(incident_list, incidents_per_page)

        try:
            incident_list = p.page(page)
        except (PageNotAnInteger, EmptyPage):
            incident_list = p.page(1)

    return render(request, 'events/table.html', {
        'incident_list': incident_list,
        'incident_view': incident_view,
        'order_param': order_param,
        'asc': asc,
        'incident_show_id': settings.INCIDENT_SHOW_ID
    }) 
Example #27
Source File: views.py    From woid with Apache License 2.0 5 votes vote down vote up
def stories(request, service, queryset, subtitle):
    paginator = Paginator(queryset, 100)
    page = request.GET.get('page')
    try:
        stories = paginator.page(page)
    except PageNotAnInteger:
        stories = paginator.page(1)
    except EmptyPage:
        stories = paginator.page(paginator.num_pages)

    if stories.number > 1:
        start = (stories.number - 1) * 100 + 1
    else:
        start = 1

    if 'application/json' in request.META.get('HTTP_ACCEPT'):
        stories_dict = map(lambda story: story.to_dict(), stories)
        dump = json.dumps({
            'service': service.to_dict(),
            'stories': stories_dict,
            'subtitle': subtitle
        })
        return HttpResponse(dump, content_type='application/json')
    else:
        return render(request, 'services/stories.html', {
            'service': service,
            'stories': stories,
            'subtitle': subtitle,
            'start': start
        }) 
Example #28
Source File: views.py    From yata with GNU General Public License v3.0 5 votes vote down vote up
def armoryLogs(request):
    try:
        if request.session.get('player'):
            player = getPlayer(request.session["player"].get("tId"))
            factionId = player.factionId

            faction = Faction.objects.filter(tId=player.factionId).first()
            if faction is None:
                selectError = 'errorMessageSub' if request.method == 'POST' else 'errorMessage'
                context = {'player': player, selectError: "Faction not found in the database."}
                return render(request, 'yata/error.html', context)

            if not player.factionAA:
                return render(request, 'faction/armory/logs.html', {'logs': []})

            logs = faction.log_set.order_by("timestamp").all()
            logtmp = dict({})
            r = 0
            m = 0
            for log in logs:
                logtmp[log.timestamp] = {"deltaMoney": (log.money - log.donationsmoney) - m, "deltaRespect": log.respect - r}
                m = (log.money - log.donationsmoney)
                r = log.respect

            logs = faction.log_set.order_by("-timestamp").all()
            for log in logs:
                log.deltaMoney = logtmp[log.timestamp]["deltaMoney"]
                log.deltaRespect = logtmp[log.timestamp]["deltaRespect"]

            logs = Paginator(logs, 7).get_page(request.GET.get('page'))

            return render(request, 'faction/armory/logs.html', {'logs': logs})

        else:
            return returnError(type=403, msg="You might want to log in.")

    except Exception as e:
        return returnError(exc=e, session=request.session)


# SECTION: big brother 
Example #29
Source File: views.py    From Python24 with MIT License 5 votes vote down vote up
def test4(request, index):
    """数据获取后的分业操作"""
    bookinfos = BookInfo.objects.all()

    # 对获取到的数据使用分液器进行分页,每页显示2个
    paginator = Paginator(bookinfos, 2)

    if index == "":
        index = '1'

    # 使用分液器的page函数获取第几页的数据,默认1开始
    current_page = paginator.page(int(index))

    context = {
        'current_page': current_page,
    }

    """
        paginator对象: 方法init(列表,int每页显示的条数)
                        方法page(m):返回Page对象,表示第m页的数据,下标以1开始
                        属性page_range:返回页码列表,从1开始,例如[1, 2, 3, 4]
                        属性count:返回对象总数
                        属性num_pages:返回页面总数
                        
        paginator.page对象:属性number:返回当前是第几页,从1开始
                            属性paginator:当前页对应的Paginator对象
                            方法has_next():如果有下一页返回True
                            方法has_previous():如果有上一页返回True
                            属性object_list:返回当前页对象的列表
                            方法len():返回当前页面对象的个数
        
    """

    return render(request, 'Book/test4.html', context) 
Example #30
Source File: views.py    From Pytition with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def org_profile(request, orgslugname):
    try:
        user = get_session_user(request)
    except:
        user = None
    try:
        org = Organization.objects.get(slugname=orgslugname)
    except Organization.DoesNotExist:
        raise Http404(_("not found"))

    petitions = org.petition_set.filter(published=True).order_by('-id')
    paginator = Paginator(petitions, settings.PAGINATOR_COUNT)
    page = request.GET.get('page')
    petitions = paginator.get_page(page)

    ctx = {'org': org,
           'petitions': petitions}

    # if a user is logged-in, put it in the context, it will feed the navbar dropdown
    if user is not None:
        ctx['user'] = user

    return render(request, "petition/org_profile.html", ctx)


# /get_user_list
# get the list of users