Python django.core.paginator 模块,Paginator() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.core.paginator.Paginator()

项目:oscar-wagtail-demo    作者:pgovers    | 项目源码 | 文件源码
def get_context(self, request):
        # Get blogs
        blogs = self.blogs

        # Filter by tag
        tag = request.GET.get('tag')
        if tag:
            blogs = blogs.filter(tags__name=tag)

        # Pagination
        page = request.GET.get('page')
        paginator = Paginator(blogs, 10)  # Show 10 blogs per page
        try:
            blogs = paginator.page(page)
        except PageNotAnInteger:
            blogs = paginator.page(1)
        except EmptyPage:
            blogs = paginator.page(paginator.num_pages)

        # Update template context
        context = super(BlogIndexPage, self).get_context(request)
        context['blogs'] = blogs
        return context
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def selected_category(request):
    """
    Returns books from selected category.
    """
    user = get_object_or_404(TheUser, auth_token=request.data.get('user_token'))
    category = get_object_or_404(Category, id=request.data.get('category_id'))

    books = Book.objects.filter(id_category=category).order_by('book_name')
    filtered_books = Book.exclude_private_books(user.id_user, books)

    paginator = Paginator(filtered_books, OUTPUT_BOOKS_PER_PAGE)
    page = paginator.page(request.data.get('page'))
    next_page = page.has_next()
    page_books = page.object_list

    return Response({'status': 200,
                     'detail': 'successful',
                     'data': {'books': [BookSerializer(book).data for book in page_books],
                              'next_page': page.next_page_number() if next_page else 0}})


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def find_book(request):
    """
    Generates list with books of data which user entered. At first it check full equality in name,
    after tries to check if contains some part of entered data.
    """
    user = get_object_or_404(TheUser, auth_token=request.data.get('user_token'))
    search_data = request.data.get('search_term')

    filtered_books = Book.exclude_private_books(user.id_user, Book.fetch_books(search_data))

    paginator = Paginator(filtered_books, OUTPUT_BOOKS_PER_PAGE)
    page = paginator.page(request.data.get('page'))
    next_page = page.has_next()
    page_books = page.object_list

    return Response({'status': 200,
                     'detail': 'successful',
                     'data': {'books': [BookSerializer(book).data for book in page_books],
                              'next_page': page.next_page_number() if next_page else 0}})
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def bookmark_list(request):
    all_bookmarks = request.user.bookmarkvideo_set.select_related('video')

    # ?? ??? ???? ?????? ??
    paginator = Paginator(all_bookmarks, 5)
    page = request.GET.get('page')
    try:
        bookmarks = paginator.page(page)
    except PageNotAnInteger:
        bookmarks = paginator.page(1)
    except EmptyPage:
        bookmarks = paginator.page(paginator.num_pages)

    context = {
        'bookmarks': bookmarks,
    }
    return render(request, 'video/bookmark_list.html', context)
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
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 ''
项目:oglasi    作者:stralz    | 项目源码 | 文件源码
def get_user_profile(request, username):
    user = User.objects.get(username=username)
    oglasi = Oglas.objects.filter(vlasnik=user)
    emp = Employee.objects.filter(user=user)
    if len(emp) > 0:
        employee = emp[0]
    else:
        employee = False

    paginator = Paginator(oglasi, 8)  # Show 25 contacts per page
    page_request_var = "page"
    page = request.GET.get(page_request_var)
    try:
        queryset = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        queryset = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        queryset = paginator.page(paginator.num_pages)

    return render(request, 'music/user_profile.html', {'user': user, 'oglasi': queryset, 'employee': employee, 'request': request, 'kategorije': Kategorija.objects.all(), "page_request_var": page_request_var})
项目:django-bootstrap4    作者:zostera    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(PaginationView, self).get_context_data(**kwargs)
        lines = []
        for i in range(200):
            lines.append('Line %s' % (i + 1))
        paginator = Paginator(lines, 10)
        page = self.request.GET.get('page')
        try:
            show_lines = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            show_lines = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            show_lines = paginator.page(paginator.num_pages)
        context['lines'] = show_lines
        return context
项目:dprr-django    作者:kingsdigitallab    | 项目源码 | 文件源码
def serve_listing(self, request):
        """Renders the children pages."""
        pages = self.children

        # Pagination
        page = request.GET.get('page')
        paginator = Paginator(pages, settings.ITEMS_PER_PAGE)

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

        return render(request, self.get_template(request),
                      {'self': self, 'pages': pages})
项目:BioQueue    作者:liyao001    | 项目源码 | 文件源码
def query_job(request):
    if request.user.is_superuser:
        job_list = Queue.objects.order_by('-create_time').all()
    else:
        job_list = Queue.objects.filter(user_id=request.user.id).order_by('-create_time').all()
    paginator = Paginator(job_list, 12)

    page = request.GET.get('page')
    '''
    try:
        jobs = paginator.page(page)
    except PageNotAnInteger:
        jobs = paginator.page(1)
    except EmptyPage:
        jobs = paginator.page(paginator.num_pages)
    '''
    jobs = page_info(paginator, page)
    dt, du, dp = get_disk_quota_info(request.user.id)
    return render(request, 'ui/query_job.html', {'job_list': jobs, 't_disk': dt, 'u_disk': du, 'disk_per': dp})
项目:quora-django    作者:hndrxr    | 项目源码 | 文件源码
def index(request, page):
    if not request.user.is_authenticated:
        return redirect('account:signup')
    profile = Profile.objects.get(user=request.user)
    following = Follow.objects.filter(profile=profile).all()
    followed_topics = []
    for topic in following:
        followed_topics.append(topic.topic)
    queries = [Q(topic=topic) for topic in followed_topics]
    if queries:
        query = queries.pop()
        for item in queries:
            query |= item
        questions = Question.objects.filter(query).order_by('-created_at').all()
    else:
        questions = []
    paginator = Paginator(questions, 10)
    questions = paginator.page(page)
    print(questions)
    return render(request, "question/index.html", {
        "questions": questions, "following": followed_topics
    })
项目:dart    作者:lmco    | 项目源码 | 文件源码
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
项目:dart    作者:lmco    | 项目源码 | 文件源码
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
项目:admintools    作者:openstates    | 项目源码 | 文件源码
def _get_pagination(objects_list, request):
    paginator = Paginator(objects_list, 20)
    try:
        page = int(request.GET.get('page', '1'))
    except:
        page = 1
    try:
        objects = paginator.page(page)
    except(EmptyPage, InvalidPage):
        objects = paginator.page(1)

    # page_range to show at bottom of table
    index = objects.number - 1
    max_index = len(paginator.page_range)
    start_index = index - 4 if index >= 4 else 0
    end_index = index + 4 if index <= max_index - 4 else max_index
    page_range = paginator.page_range[start_index:end_index]

    return objects, page_range


# Status Page
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def faircoin_history(request, resource_id):
    resource = get_object_or_404(EconomicResource, id=resource_id)
    event_list = resource.events.all()
    agent = get_agent(request)
    init = {"quantity": resource.quantity,}
    unit = resource.resource_type.unit

    paginator = Paginator(event_list, 25)

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

    return render_to_response("work/faircoin_history.html", {
        "resource": resource,
        "agent": agent,
        "unit": unit,
        "events": events,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def all_contributions(request):
    event_list = EconomicEvent.objects.filter(is_contribution=True)
    paginator = Paginator(event_list, 25)

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

    return render_to_response("valueaccounting/all_contributions.html", {
        "events": events,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def project_wip(request, project_id):
    #import pdb; pdb.set_trace()
    project = get_object_or_404(EconomicAgent, pk=project_id)
    process_list = project.wip()
    paginator = Paginator(process_list, 25)

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

    return render_to_response("valueaccounting/project_wip.html", {
        "project": project,
        "processes": processes,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def todo_history(request):
    #import pdb; pdb.set_trace()
    todo_list = Commitment.objects.finished_todos().order_by('-due_date',)

    paginator = Paginator(todo_list, 25)
    page = request.GET.get('page')
    try:
        todos = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        todos = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        todos = paginator.page(paginator.num_pages)

    return render_to_response("valueaccounting/todo_history.html", {
        "todos": todos,
    }, context_instance=RequestContext(request))
项目:nrp    作者:django-rea    | 项目源码 | 文件源码
def open_todos(request):
    #import pdb; pdb.set_trace()
    todo_list = Commitment.objects.todos().order_by('-due_date',)

    paginator = Paginator(todo_list, 25)
    page = request.GET.get('page')
    try:
        todos = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        todos = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        todos = paginator.page(paginator.num_pages)

    return render_to_response("valueaccounting/open_todos.html", {
        "todos": todos,
    }, context_instance=RequestContext(request))
项目:weibo-spider    作者:bowenpay    | 项目源码 | 文件源码
def weibo_list(request):
    context = {}
    # ????
    params = request.GET.copy()
    _obj_list = Weibo.objects.order_by('-id')

    paginator = Paginator(_obj_list, 50 )  # Show 10 contacts per page

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

    context.update({
        "active_nav": "weibos.weibo",
        "weibos": _objs,
        "params": params
    })
    return render_to_response('weibos/weibo_list.html', {}, context_instance=RequestContext(request, context))
项目:pandachaika    作者:pandabuilder    | 项目源码 | 文件源码
def image_viewer(request: HttpRequest, archive: int, page: int) -> HttpResponse:

    images = Image.objects.filter(archive=archive, extracted=True)
    if not images:
        raise Http404("Archive " + str(archive) + " has no extracted images")

    paginator = Paginator(images, 1)
    try:
        image = paginator.page(page)
    except (InvalidPage, EmptyPage):
        image = paginator.page(paginator.num_pages)

    image_object = image.object_list[0]

    if image_object.image_width / image_object.image_height > 1:
        image_object.is_horizontal = True

    d = {'image': image, 'backurl': redirect(image.object_list[0].archive).url,
         'images_range': range(1, images.count() + 1), 'image_object': image_object}

    return render(request, "viewer/image_viewer.html", d)
项目:wms    作者:aabdulwahed    | 项目源码 | 文件源码
def device(request):
    values = {}
    # collect api_key and device id
    devices = []
    for s in Service.objects.all():
        for d in WorkSpace.objects.filter(service=s):
            devices.append({'apikey':s.apikey, 'device_id':d.ws_id, 'workspace':d.entity_name, 'address':d.address, 'maxsize':d.maxsize})
    paginator = Paginator(devices, 11)
    try:
        page = request.GET.get('page')
        results = paginator.page(page)
    except PageNotAnInteger:
        results = paginator.page(1)
    except EmptyPage:
        results = paginator.page(paginator.num_pages)
    values = {'results':results}
    return render_to_response("RFID.html", values, context_instance=RequestContext(request))
项目:django-konfera    作者:pyconsk    | 项目源码 | 文件源码
def event_public_tickets(request, slug):
    event = get_object_or_404(Event.objects.published(), slug=slug)
    context = dict()
    update_event_context(event, context)

    available_tickets = event.tickettype_set.filter(accessibility=TicketType.PUBLIC)\
        .exclude(attendee_type=TicketType.AID).exclude(attendee_type=TicketType.VOLUNTEER)\
        .exclude(attendee_type=TicketType.PRESS).order_by('price', 'title')
    available_tickets = [t for t in available_tickets
                         if t._get_current_status() in (TicketType.ACTIVE, TicketType.SOLDOUT)]
    paginator = Paginator(available_tickets, 10)
    page = request.GET.get('page')

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

    context['tickets'] = available_tickets
    context['dispaly_ticket_availability'] = settings.DISPLAY_TICKET_AVAILABILITY

    return render(request=request, template_name='konfera/event/public_tickets.html', context=context)
项目:autoreg    作者:pbeyssac    | 项目源码 | 文件源码
def rqloglist(request):
  if request.method != "GET":
    raise SuspiciousOperation
  if not request.user.is_authenticated() or not request.user.is_active:
    raise PermissionDenied
  is_admin = check_is_admin(request.user.username)
  if not is_admin:
    raise PermissionDenied
  log = models.RequestsLog.objects.all().order_by('-date')
  paginator = Paginator(log, 100)

  page = request.GET.get('page')
  try:
    logpage = paginator.page(page)
  except PageNotAnInteger:
    logpage = paginator.page(1)
  except EmptyPage:
    logpage = paginator.page(paginator.num_pages)

  vars = { 'list': logpage }
  return render(request, 'requests/rqloglist.html', vars)
项目:autoreg    作者:pbeyssac    | 项目源码 | 文件源码
def loglist(request):
  if request.method != "GET":
    raise SuspiciousOperation
  if not request.user.is_authenticated():
    raise PermissionDenied
  is_admin = check_is_admin(request.user.username)
  if not is_admin:
    raise PermissionDenied
  log = Log.objects.all().order_by('-date')
  paginator = Paginator(log, 100)

  page = request.GET.get('page')
  try:
    logpage = paginator.page(page)
  except PageNotAnInteger:
    logpage = paginator.page(1)
  except EmptyPage:
    logpage = paginator.page(paginator.num_pages)

  vars = {'list': logpage }

  return render(request, 'logs/log.html', vars)
项目:2017.1-PlataformaJogosUnB    作者:fga-gpp-mds    | 项目源码 | 文件源码
def paginate(self, page, per_page, data):
        list_games = data
        paginator = Paginator(list_games, per_page)

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

        interval_range = self.get_pagination_range(page, paginator.num_pages)

        list_games = GameSerializer(games.object_list, many=True).data
        paginated = {
            "games": list_games,
            "info": {
                "range_start": interval_range[0],
                "range_end": interval_range[1],
                "num_pages": paginator.num_pages,
                "page": page
            }
        }
        return paginated
项目:ploghub    作者:ploggingdev    | 项目源码 | 文件源码
def get(self, request):
        user = request.user
        comments = Comment.objects.all().filter(deleted=False).filter(user=user).order_by('-created')
        posts = Post.objects.all().filter(deleted=False).filter(user=user).order_by('-created')

        total_count = Comment.objects.all().filter(deleted=False).filter(user=user).count() + Post.objects.all().filter(deleted=False).filter(user=user).count()

        all_items = chain(comments, posts)
        all_items = sorted(all_items, key=attrgetter('created'), reverse=True)

        paginator = Paginator(all_items, self.paginate_by)

        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 (e.g. 9999), deliver last page of results.
            posts = paginator.page(paginator.num_pages)

        return render(request, self.template_name, {'posts': posts})
项目:verbes    作者:larose    | 项目源码 | 文件源码
def get_context_data(self):
        context = {}

        attempts = Attempt.objects.own(self.request).order_by('-created_time')
        paginator = Paginator(attempts, 10)
        page = self.request.GET.get('page')

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

        context['attempts'] = attempts

        success_rate = None
        if Attempt.objects.num_attempts(self.request):
            success_rate = 100 * (Attempt.objects.num_good_attempts(self.request) / Attempt.objects.num_attempts(self.request))
            success_rate = round(success_rate, 1)

        context['success_rate'] = success_rate

        return context
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
            context = super(ScienceListView, self).get_context_data(**kwargs)

            science_lists = self.get_queryset()

            paginator = Paginator(science_lists, self.paginate_by)
            try:
                page = self.kwargs['page']
            except:
                page = 1

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

            context['scienceart'] = scienceart
            context['sci'] = self.kwargs['sci_slug']

            return context
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
            context = super(TermListView, self).get_context_data(**kwargs)

            term_lists = self.get_queryset()

            paginator = Paginator(term_lists, self.paginate_by)
            try:
                page = self.kwargs['page']
            except:
                page = 1

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

            context['terms'] = terms
            context['term_slug'] = self.kwargs['term_slug']

            return context
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(VideoListView, self).get_context_data(**kwargs)

        video_lists = self.get_queryset()

        paginator = Paginator(video_lists, self.paginate_by)
        try:
            page = self.kwargs['page']
        except:
            page = 1

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

        context['videos'] = videos
        context['vid'] = self.kwargs['vid_slug']

        return context
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(TwitsListView, self).get_context_data(**kwargs)

        twit_lists = self.get_queryset()

        paginator = Paginator(twit_lists, self.paginate_by)
        try:
            page = self.kwargs['page']
        except:
            page = 1

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

        context['twits'] = twits
        context['twit_slug'] = self.kwargs['twit_slug']

        return context
项目:django-blog    作者:shawon922    | 项目源码 | 文件源码
def index(request):
    posts_list = Post.objects.all()  # .order_by("-timestamp")

    paginator = Paginator(posts_list, 5)
    page_var = 'page1'
    page = request.GET.get(page_var)

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

    context = {
        'page_title': 'List of Posts',
        'posts': posts,
        'page_var': page_var
    }

    return render(request, 'posts/index.html', context)
项目:marvin-django    作者:programa-stic    | 项目源码 | 文件源码
def list_vulns(request, vuln_list):
    myList = []
    for vt in vuln_list:
        positives = VulnerabilityResult.objects.all().filter(name=vt)
        apps = set(App.objects.filter(vulnerabilityresult__name=vt))
        myList.append({"name":vt, "count":positives.count, "appcount":len(apps)})
        myList.sort(key= lambda vt:vt['appcount'], reverse=True)
    paginator = Paginator(myList,20)
    page = request.GET.get('page')
    try:
        vulns = paginator.page(page)
    except PageNotAnInteger:
        vulns = paginator.page(1)
    except EmptyPage:
        vulns = paginator.page(paginator.num_pages)
    context = {'vulns':vulns}
    return render_to_response('frontpage/static_vulns.html', RequestContext(request, context))
项目:Django-Web-Development-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def movie_list(request):
    paginator = Paginator(TOP_MOVIE_LIST, 25)

    page_number = request.GET.get("page")
    try:
        page = paginator.page(page_number)
    except PageNotAnInteger:
        # If page is not an integer, show first page.
        page = paginator.page(1)
    except EmptyPage:
        # If page is out of range, show last existing page.
        page = paginator.page(paginator.num_pages)

    context = {
        "object_list": page,
    }
    return render(request, "movies/movie_list.html", context)
项目:Guazi    作者:xgkmxxx    | 项目源码 | 文件源码
def list_guazi(request):
    after_range_num = 5
    before_range_num = 4
    page_size = 20
    Guazi_list = GuaziCar.objects.all().order_by('-id')
    paginator = Paginator(Guazi_list, page_size)
    try:
        page = int(request.GET.get('page','1'))
        if page < 1:
            page=1
    except ValueError:
        page=1
    try:
        carlist = paginator.page(page)
    except (EmptyPage,InvalidPage,PageNotAnInteger):
        carlist = paginator.page(1)
    if page >= after_range_num:
        page_range = list(paginator.page_range)[page-after_range_num:page+before_range_num]
    else:
        page_range = list(paginator.page_range)[0:int(page)+before_range_num]
    return render(request, 'guazi.html', {'guazi_list': carlist, 'page_range': page_range})
项目:restless-haystack    作者:CraveFood    | 项目源码 | 文件源码
def get_page(self, data):
        try:
            page_no = int(self.request.GET.get(self.page_attribute_name, 1))
        except (TypeError, ValueError):
            raise NotFound('Invalid page number.')
        if page_no < 1:
            raise NotFound('Page number should be 1 or greater.')
        # Explicitly evaluate data before sending it to Paginator, otherwise
        # (at least in the case of RelatedSearchQuerySet) the total count
        # goes completely wrong
        # see: https://github.com/django-haystack/django-haystack/issues/362
        data[:self.results_per_page]
        paginator = Paginator(data, self.results_per_page)

        try:
            page = paginator.page(page_no)
        except InvalidPage:
            raise NotFound('No such page!')
        return page
项目:bart-crime    作者:ben174    | 项目源码 | 文件源码
def view_station(request, station_id):
    station = get_object_or_404(Station, abbreviation=station_id)
    incidents = Incident.objects.filter(
        station__id=station.id,
    ).order_by('-incident_dt')
    incidents_count = len(incidents)
    paginator = Paginator(incidents, 25)

    page = request.GET.get('page')
    try:
        incidents = paginator.page(page)
    except PageNotAnInteger:
        incidents = paginator.page(1)
    except EmptyPage:
        incidents = paginator.page(paginator.num_pages)

    return render(request, 'station.html', {'incidents_count': incidents_count,
                                            'station': station,
                                            'incidents': incidents})
项目:bart-crime    作者:ben174    | 项目源码 | 文件源码
def incidents_for_tag(request, slug):
    tag = get_object_or_404(Tag, slug=slug)
    incidents = Incident.objects.filter(
        tags__id=tag.id,
    ).order_by('-incident_dt')
    incidents_count = len(incidents)
    paginator = Paginator(incidents, 25)

    page = request.GET.get('page')
    try:
        incidents = paginator.page(page)
    except PageNotAnInteger:
        incidents = paginator.page(1)
    except EmptyPage:
        incidents = paginator.page(paginator.num_pages)

    return render(request, 'tag.html', {'tag': tag, 'incidents': incidents,
                                        'incidents_count': incidents_count})


# pylint: disable=too-many-ancestors
项目:beg-django-e-commerce    作者:Apress    | 项目源码 | 文件源码
def results(request, template_name="search/results.html"):
    """ template for displaying settings.PRODUCTS_PER_PAGE paginated product results """
    # get current search phrase
    q = request.GET.get('q', '')
    # get current page number. Set to 1 is missing or invalid
    try:
        page = int(request.GET.get('page', 1))
    except ValueError:
        page = 1

    matching = search.products(q).get('products', [])
    # generate the pagintor object
    paginator = Paginator(matching, 
                          settings.PRODUCTS_PER_PAGE)
    try:
        results = paginator.page(page).object_list
    except (InvalidPage, EmptyPage):
        results = paginator.page(1).object_list

    search.store(request, q)

    page_title = 'Search Results for: ' + q
    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
项目:stepic_web_project    作者:kovtunos    | 项目源码 | 文件源码
def paginate(request, qs):
    try:
        limit = int(request.GET.get('limit', 10))
    except ValueError:
        limit = 10
    if limit > 100:
        limit = 10

    try:
        page = int(request.GET.get('page', 1))
    except ValueError:
        raise Http404

    paginator = Paginator(qs, limit)

    try:
        page = paginator.page(page)
    except EmptyPage:
        page = paginator.page(paginator.num_pages)
    return page, paginator
项目:nzhuts    作者:jordij    | 项目源码 | 文件源码
def get_context(self, request):
        context = super(HutIndexPage, self).get_context(request)
        page = request.GET.get('page')
        tag = request.GET.get('tag')
        pages = HutPage.objects.child_of(self).live()
        if tag:
            pages = pages.filter(facilities__slug__iexact=tag)
            context['tag'] = Tag.objects.get(slug__iexact=tag)
        paginator = Paginator(pages, 10)  # Show 10 huts per page
        try:
            pages = paginator.page(page)
        except PageNotAnInteger:
            pages = paginator.page(1)
        except EmptyPage:
            pages = paginator.page(paginator.num_pages)
        context['children'] = pages
        return context
项目:DTV    作者:Airwavess    | 项目源码 | 文件源码
def index(request):
    template = get_template('index.html')

    attractions_data = Attractions.objects.all()
    paginator = Paginator(attractions_data, 5) # Show 10 content per page
    page = request.GET.get('page')

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

    index = content.number
    max_index = len(paginator.page_range)
    start_index = max_index - 7 if index >= max_index - 5 else index - 1 if index != 1 else 1
    end_index = max_index + 1 if index >= max_index - 6 else index + 7 if index != 1 else index + 8
    page_range = range(start_index, end_index)

    html = template.render(locals())
    return HttpResponse(html)
项目:stepic_web_project    作者:izverg23    | 项目源码 | 文件源码
def index(request) :
    pageLimit = 10
    #Entry.objects.order_by(Coalesce('summary', 'headline').desc()) #asc()
    qwests = Question.objects.all().order_by('-id')

    from django.core.paginator import Paginator

    page = request.GET.get('page') or 1
    try :
        page = int(page)
    except ValueError :
        page = 1
    paginator = Paginator(qwests, pageLimit)
    paginator.baseurl = '/?page='
    try :
        page = paginator.page(page)
    except EmptyPage :
        page = paginator.page(paginator.num_pages)
    return render(request, 'questionList.html', {
        'title' : 'qwests and answers',
        'list' : page.object_list,
        'paginator' : paginator, 
        'page' : page,
    })
项目:stepic_web_project    作者:izverg23    | 项目源码 | 文件源码
def popular(request) :
    pageLimit = 10
    #Entry.objects.order_by(Coalesce('summary', 'headline').desc()) #asc()
    qwests = Question.objects.all().order_by('-likes')

    from django.core.paginator import Paginator

    page = request.GET.get('page') or 1
    try :
        page = int(page)
    except ValueError :
        page = 1
    paginator = Paginator(qwests, pageLimit)
    paginator.baseurl = '/?page='
    try :
        page = paginator.page(page)
    except EmptyPage :
        page = paginator.page(paginator.num_pages)
    return render(request, 'questionList.html', {
        'title' : 'popular quests',
        'list' : page.object_list,
        'paginator' : paginator, 
        'page' : page,
    })
项目:DjangoSpree    作者:prakharchoudhary    | 项目源码 | 文件源码
def post_list(request, tag_slug=None):
    object_list = Post.published.all()
    tag = None

    if tag_slug:
        tag = get_object_or_404(Tag, slug=tag_slug)
        object_list = object_list.filter(tags__in=[tag])

    paginator = Paginator(object_list, 3) # 3 posts in each page
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer deliver the 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,'blog/post/list.html',{'page': page, 'posts': posts, 'tag':tag})
项目:DjangoSpree    作者:prakharchoudhary    | 项目源码 | 文件源码
def image_list(request):
    images = Image.objects.all()
    paginator = Paginator(images, 8)
    page = request.GET.get('page')
    try:
        images = paginator.page(page)
        images_by_popularity = Image.objects.order_by('-total_likes')

    except PageNotAnInteger:
        if request.is_ajax():
            # If page is not an integer deliver the first page
            images = paginator.page(1)

    except EmptyPage:
        if request.is_ajax():
            # If the request AJAX and the page is out of range
            # return an empty page
            return HttpResponse('')
        # If page is out of range deliver last page of results
        images = paginator.page(paginator.num_pages)

    if request.is_ajax():
        return render(request, 'images/image/list_ajax.html',{'section': 'images', 'images': images})

    return render(request, 'images/image/list.html', {'section': 'images', 'images': images})
项目:WPS-3rd    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def album_detail(request, pk):
    album = get_object_or_404(Album, pk=pk)
    photo_list = album.photo_set.all()
    paginator = Paginator(photo_list, 4)

    page = request.GET.get('page')
    try:
        photos = paginator.page(page)
    except PageNotAnInteger:
        photos = paginator.page(1)
    except EmptyPage:
        photos = paginator.page(paginator.num_pages)

    context = {
        'album': album,
        'photos': photos,
    }
    # template_file = 'photo/album_detail.html'
    template_file = 'photo/ajax_album_detail.html'
    return render(request, template_file, context)
项目:dao_manage    作者:houziyu    | 项目源码 | 文件源码
def html_page(request):
    service_name  = request.GET.get('service_name')
    log_path = dao_config.log_dir_master
    service_name_path = log_path + service_name
    all_file = []
    for i in os.listdir(service_name_path):
        file_path = service_name_path +'/' + i
        if os.path.isfile(file_path):
            all_file.append([i,file_path])
    print(all_file)
    all_file = sorted(all_file, key=lambda file_name: file_name[1])
    paginator = Paginator(all_file, 10)  # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    return render(request, 'cat_down_log.html', {"contacts": contacts,'service_name':[service_name]})
项目:my_oms    作者:jwh5566    | 项目源码 | 文件源码
def host_list(request):
    """
    List all Hosts
    """
    user = request.user
    host_list = HostList.objects.all().order_by('-status')
    # host_list = HostList.objects.all()
    paginator = Paginator(host_list,10)

    try:
        page = int(request.GET.get('page','1'))
    except ValueError:
        page = 1

    try:
        host_list = paginator.page(page)
    except :
        all_host = paginator.page(paginator.num_pages)

    return render(request, 'host_list.html', {'host_list': host_list, 'page': page, 'paginator':paginator})
    # return render(request, 'host_list.html',{'host_list': host_list})
项目:my_oms    作者:jwh5566    | 项目源码 | 文件源码
def system_install_record(request):
    """
    List all operating system installation records
    """

    user = request.user

    record = InstallRecord.objects.all().order_by('-install_date')
    paginator = Paginator(record,10)

    try:
        page = int(request.GET.get('page','1'))
    except ValueError:
        page = 1

    try:
        record = paginator.page(page)
    except :
        record = paginator.page(paginator.num_pages)

    return render(request, 'install_record_list.html', {'record': record, 'page': page, 'paginator':paginator})