Пример #1
0
def index(request, page=1, format=None):
    try:
        featured_quote = Quote.objects.filter(featured=True) \
                                      .order_by('?')[:1][0]
        quotes = Quote.objects.all() \
                              .exclude(id=featured_quote.id)
    except IndexError:
        quotes = Quote.objects.all()
    quotes = Paginator(quotes, PER_PAGE).page(
        page or 1
    )

    if format == 'json':
        data = {
            'hasNext': quotes.has_next(),
            'quotes': []
        }
        for quote in quotes:
            data['quotes'].append(quote.serialize())
        return HttpResponse(json.dumps(data), mimetype='application/json')
    else:
        title = "defprogramming: quotes about coding"
        description = "Quotes about programming, coding, computer science, " \
                      "debugging, software industry, startups and motivation."
        base_url_pagination = reverse('root')
        return render_to_response('quotes/index.html',
                                  locals(),
                                  context_instance=RequestContext(request))
Пример #2
0
def paginate(
    request,
    klass,
    per_page=4,
    page_number=1,
):
    query = request.GET
    page_number = query.get('page_number', page_number)
    per_page = query.get('per_page', per_page)
    try:
        objects = klass.objects.all()
        page = Paginator(objects, per_page=per_page).get_page(page_number)
    except:
        objects = klass
        page = Paginator(objects, per_page=per_page).get_page(page_number)
    is_paginated = page.has_other_pages()
    current_page = page.number
    last_page = page.paginator.num_pages
    has_prev = page.has_previous()
    has_next = page.has_next()
    next_page = page.next_page_number() if has_next else ''
    prev_page = page.previous_page_number() if has_prev else ''
    pages_list = page.paginator.page_range
    pages_list = list(pages_list)
    return locals()
Пример #3
0
def list_users(world_id,
               page,
               page_size,
               search_term,
               trait_badges_map=None) -> object:
    qs = User.objects.filter(world_id=world_id, show_publicly=True)
    if search_term:
        qs = qs.filter(profile__display_name__icontains=search_term)

    try:
        p = Paginator(
            qs.order_by("id").values("id", "profile", "traits"),
            page_size).page(page)
        return {
            "results": [
                dict(
                    id=str(u["id"]),
                    profile=u["profile"],
                    badges=sorted(
                        list({
                            badge
                            for trait, badge in trait_badges_map.items()
                            if trait in u["traits"]
                        })) if trait_badges_map else [],
                ) for u in p.object_list
            ],
            "isLastPage":
            not p.has_next(),
        }
    except InvalidPage:
        return {
            "results": [],
            "isLastPage": True,
        }
Пример #4
0
def paginate(posts, query):
    page_number  = query.get('page_number')
    # per_page     = query.get('per_page', CatalogueConfig.get_solo().posts_per_page)
    per_page     = query.get('per_page', 8)
    page         = Paginator(posts, per_page=per_page).get_page(page_number)
    page_posts   = PostSerializer(page, many=True, read_only=True).data
    is_paginated = page.has_other_pages()
    current_page = page.number
    last_page    = page.paginator.num_pages
    pages_list   = page.paginator.page_range
    has_prev     = page.has_previous()
    has_next     = page.has_next()
    next_page    = page.next_page_number() if has_next else ''
    prev_page    = page.previous_page_number() if has_prev else ''
    response     = {
        'page_posts':   page_posts,
        'is_paginated': is_paginated,
        'current_page': current_page,
        'last_page':    last_page,
        'pages_list':   list(pages_list),
        'has_prev':     has_prev,
        'has_next':     has_next,
        'next_page':    next_page,
        'prev_page':    prev_page,
    }
    return response 
Пример #5
0
def get_imgs(request, page=None, pk=None):
    """
    Returns some JSON corresponding to a list of image thumbnails.
    These correspond to Image.objects.all() and are paginated.
    """
    
    if page is not None:
        IMGS_PER_REQ = 2
        json_dict, images = {}, {}
        
        p = Paginator(Image.objects.all(), IMGS_PER_REQ).page(page)
        imgs = p.object_list  
        for i in imgs:
            images[i.pk] = render_to_string('image_fragment.html', {'images': [i]})
        
        json_dict['images'] = images
        json_dict['next_page'] = p.next_page_number() if p.has_next() else 0
        json_dict['prev_page'] = p.previous_page_number() if p.has_previous() else 0
        return HttpResponse(simplejson.dumps(json_dict))
        
    elif pk is not None:
        return render_to_response(
            'image_fragment.html', 
            {'images': [get_object_or_404(Image, pk=pk)]}
        )
def lazyLoadGroup(request):
    """A function that will return html to append to the
    userlist from the queryset of the users in the selected group."""
    if request.is_ajax and request.user.is_authenticated and hasattr(
            request.user, 'userprofile'):
        selected_group = getGroupSelection(request)
        no_page = False
        page = request.POST["page"]
        selected_group = getGroupSelectionUsers(request)
        selected_group = selected_group.order_by("-herolevels__general_level")
        group = Paginator(selected_group, 25)
        try:
            group = group.page(page)
        except PageNotAnInteger:
            group = group.page(2)
        except EmptyPage:
            group = group.page(group.num_pages)
            no_page = True
        calling_group_html = loader.render_to_string(
            'community/includes/groupmembersextra.html', {'group': group})
        output_data = {
            'calling_group_html': calling_group_html,
            'has_next': group.has_next(),
            "no_page": no_page
        }
        return JsonResponse(output_data)
Пример #7
0
def pagination(posts, posts_per_page=10, page=1):
#   posts per page
    start_pos = (int(page)-1) * posts_per_page
    end_pos = start_pos + posts_per_page
    posts_of_present_page = posts[start_pos : end_pos]

    paginator = Paginator(posts, posts_per_page).page(page)
    has_next = paginator.has_next()
    has_previous = paginator.has_previous()
    nextpage = page
    previous_page = page
    if has_next:
        nextpage = paginator.next_page_number()
    if has_previous:
        previous_page = paginator.previous_page_number()

    custom_paginator = {
                               'posts' : posts_of_present_page,
                               'paginator' : paginator,
                               'has_next' : has_next,
                               'has_previous' : has_previous,
                               'nextpage' : nextpage,
                               'previous_page' : previous_page,
                       }
    return custom_paginator
Пример #8
0
def get_user_detections_page(user, page, preload=False):
    timeout = 48 * 3600 if preload else 10 * 60
    data = cache.get("user_{}_recent_detections_{}".format(user.id, page))
    if preload or not data:
        p = Paginator(
            Detection.objects.filter(user=user).order_by("-timestamp").filter(
                visible=True),
            20,
        ).page(page)
        data = {
            "has_next":
            p.has_next(),
            "has_previous":
            p.has_previous(),
            "page_number":
            page,
            "detections": [{
                "date": format_date(d.timestamp),
                "timestamp": d.timestamp,
                "img": base64.encodebytes(d.frame_content).decode(),
                "x": d.x,
                "y": d.y,
            } for d in p.object_list],
        }
        cache.set("user_{}_recent_detections_{}".format(user.id, page),
                  data,
                  timeout=timeout)
    return data
Пример #9
0
    def get(self, request):
        topic_id = request.GET.get('topic')
        try:
            page = request.GET.get('page')
        except PageNotAnInteger:
            page = 1
        q = QuestionTopic.objects.filter(under_id=topic_id).values('question')
        a = Answer.objects.filter(
            question__in=q).select_related().order_by('-time_written')

        p = Paginator(a, 5, allow_empty_first_page=False)

        global next_page

        try:
            p = p.page(page)
            # IF there is a next page it doesnt include an hidden field
            # But includes the hidden field to signal to the front end that there is no next page
            if p.has_next():
                next_page = None
            else:
                next_page = 1
        except EmptyPage:
            next_page = 1
            p = None

        return render_to_response('answers/answer_item.html', {
            'answers': p,
            'request': request,
            'next_page': next_page
        })
Пример #10
0
 def get_results(self, request, term, page, context):
     queryset = ContestProfile.objects.filter(Q(user__user__username__icontains=term) | Q(user__name__icontains=term))\
                              .select_related('user__user')
     page = Paginator(queryset, 20).page(page)
     return 'nil', page.has_next(), [
         (profile.id, 'Contest: ' + profile.user.long_display_name)
         for profile in page
     ]
Пример #11
0
 def get_results(self, request, term, page, context):
     queryset = Comment.objects.filter(
         Q(title__icontains=term) | Q(page__icontains=term))
     page = Paginator(queryset, 20).page(page)
     return 'nil', page.has_next(), [
         (comment.id, '-' * comment.level + comment.title)
         for comment in page
     ]
Пример #12
0
 def get_results(self, request, term, page, context):
     queryset = Problem.objects.filter(Q(code__icontains=term) | Q(name__icontains=term))
     if not request.user.has_perm('judge.see_private_problem'):
         filter = Q(is_public=True)
         if request.user.is_authenticated():
             filter |= Q(authors=request.user.profile)
         queryset = queryset.filter(filter)
     page = Paginator(queryset, 20).page(page)
     return 'nil', page.has_next(), [(problem.id, problem.name) for problem in page]
def resetStats(request):
    """A function that will return
    the statistics for the newly selected group."""
    if request.is_ajax and request.user.is_authenticated and hasattr(
            request.user, 'userprofile'):
        selected_group = getGroupSelectionUsers(request)
        selected_group_logs = getGroupSelection(request)
        selected_group = selected_group.order_by("-herolevels__general_level")
        group = Paginator(selected_group, 25)
        group = group.page(1)
        age_group = getAgeGroup(request)
        members = selected_group.count()
        male = selected_group.filter(userprofile__gender="M").count()
        female = selected_group.filter(userprofile__gender="F").count()
        date_month = date.today() - timedelta(days=30)
        month = selected_group_logs.filter(date__gte=date_month).count()
        admin = False
        group_s = getGroup(request)
        groupname = ''
        if group_s["custom"] != "false":
            c_group = CustomGroup.objects.get(pk=group_s["custom"])
            groupname = c_group.name
            admin = c_group.admin
        else:
            if group_s["location"] == "group-city":
                groupname = request.user.userprofile.town_or_city
            elif group_s["location"] == "group-country":
                groupname = request.user.userprofile.get_country_display()
            else:
                groupname = "global"
            if group_s["age"] == "true":
                groupname = str(groupname) + ' ' + age_group.split(' ')[0]
        average_user = round(month / members)
        average_l = selected_group.aggregate(Avg('herolevels__general_level'))
        average_level = round(average_l['herolevels__general_level__avg'])
        stats_html = loader.render_to_string(
            'community/includes/groupstats.html', {
                'groupname': groupname,
                'admin': admin,
                'members': members,
                'male': male,
                'female': female,
                'month': month,
                'average_user': average_user,
                'average_level': average_level
            })
        members_html = loader.render_to_string(
            'community/includes/groupmembers.html', {
                'group': group,
            })
        output_data = {
            'stats_html': stats_html,
            'members_html': members_html,
            'has_next': group.has_next(),
        }
        return JsonResponse(output_data)
Пример #14
0
 def get_results(self, request, term, page, context):
     queryset = Problem.objects.filter(
         Q(code__icontains=term) | Q(name__icontains=term))
     if not request.user.has_perm('judge.see_private_problem'):
         filter = Q(is_public=True)
         if request.user.is_authenticated():
             filter |= Q(authors=request.user.profile)
         queryset = queryset.filter(filter)
     page = Paginator(queryset, 20).page(page)
     return 'nil', page.has_next(), [(problem.id, problem.name)
                                     for problem in page]
Пример #15
0
 def list_identifiers(self, page_number=1, from_date=None, until_date=None,
                      set=None, microsite=None):
     headers = []
     items = Paginator(self.get_items(from_date, until_date, set, microsite), self.BATCH_SIZE).page(page_number)
     for item in items.object_list:
         header = self.repository.build_header(item)
         headers.append(header)
     next_page_number = None
     if items.has_next():
         next_page_number = items.next_page_number()
     return headers, next_page_number, items.paginator.count
Пример #16
0
 def list_records(self, page_number=1, from_date=None, until_date=None,
                  set=None, microsite=None):
     records = []
     items = Paginator(self.get_items(from_date, until_date, set, microsite), self.BATCH_SIZE).page(page_number)
     site = Site.objects.get_current()
     for item in items.object_list:
         header = self.repository.build_header(item)
         metadata = self.build_metadata(item, site)
         records.append(Record(header, metadata))
     next_page_number = None
     if items.has_next():
         next_page_number = items.next_page_number()
     return records, next_page_number, items.paginator.count
Пример #17
0
    def get(self, request):
        topics_followed = TopicFollowing.objects.filter(
            user_id=self.request.user.id).values('follows')
        questions = QuestionTopic.objects.filter(
            under_id__in=topics_followed).values('question')
        answers = Answer.objects.filter(
            question_id__in=questions).select_related()

        # Answers written by people you follow
        user_following = UserFollowings.objects.filter(
            user_id=self.request.user.id).values('is_following')
        answers2 = Answer.objects.filter(
            writer_id__in=user_following).select_related()

        # Answers upvoted by people you follow
        upvotes = UpVotes.objects.filter(
            user_id__in=user_following).select_related().values('answer')
        answers3 = Answer.objects.filter(id__in=upvotes).select_related()

        # Answers in questions followed by those you follow
        qf = QuestionFollowing.objects.filter(
            user_id=self.request.user).values('question')
        answers4 = Answer.objects.filter(question_id__in=qf)

        # Combining the result sets
        all_answers = answers | answers2 | answers3 | answers4

        already_read = AlreadyReadAnswers.objects.filter(
            user_id=self.request.user.id).values('answer')

        if int(request.GET['page']) == 1:
            all_answers = all_answers.exclude(id__in=already_read).exclude(
                writer_id=self.request.user.id)
        else:
            all_answers = all_answers.exclude(writer_id=self.request.user.id)

        all_answers = all_answers.distinct().order_by('-time_written')[:300]

        p = Paginator(all_answers, 5)
        p = p.page(request.GET['page'])

        if p.has_next():
            next_page = None
        else:
            next_page = 1

        return render_to_response('answers/answer_item.html', {
            'answers': p,
            'request': request,
            'next_page': next_page
        })
Пример #18
0
def get_paginated_data(data, page=None, limit=None, url=""):
    next_page, previous_page = None, None
    try:
        page = int(page) if page else 1
        limit = int(limit) if limit else 2
        data = Paginator(data, limit)
        data = data.page(page)
        if data.has_next():
            next_page = F"{url}&page={page+1}&limit={limit}"
        if data.has_previous():
            previous_page = F"{url}&page={page-1}&limit={limit}"
        data = list(data)
    except EmptyPage or InvalidPage:
        data = None
    return {"data": data, "next": next_page, "previous": previous_page}
Пример #19
0
def list(request, page=1, tag=None):
  page = int(page)

  entries = Entry.objects.all().filter(published=True).order_by('-pub_date')
  if tag:
    entries = TaggedItem.objects.get_by_model(entries, tag)
  
  p = Paginator(entries, 5).page(page)

  return render_to_response('blog/base_blog.html',
      { 'entries': p.object_list,
#        'all_entries': entries,
        'tag': tag,
        'older_page': p.next_page_number() if p.has_next() else None,
        'newer_page': p.previous_page_number() if p.has_previous() else None } )
Пример #20
0
def get_user_detections_page(user, page):
    data = cache.get('user_{}_recent_detections_{}'.format(user.id, page))
    if not data:
        p = Paginator(Detection.objects.filter(user=user).order_by('-timestamp').filter(visible=True), 20).page(page)
        data = {
            'has_next': p.has_next(),
            'has_previous': p.has_previous(),
            'page_number': page,
            'detections': [{
                'date': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(d.timestamp / 1000)),
                'img': base64.encodestring(d.frame_content)
            } for d in p.object_list]
        }
        cache.set('user_{}_recent_detections_{}'.format(user.id, page), data)
    return data
Пример #21
0
    def list(self, request):
        
        # Sorted by -created date
        editions = Edition.objects.all()

        return_json = OrderedDict([('href', request.build_absolute_uri('')),
                                   ('count', len(editions)),
                                   ('next', None),
                                   ('previous', None),
                                   ('template', {}),
                                   ('results', [])])

        request_page = request.GET.get('page', 1)

        try:
            page = Paginator(editions, 16, allow_empty_first_page=False).page(request_page)
        except InvalidPage:
            raise Http404("Invalid page")
        except PageNotAnInteger:
            raise Http404("Page not a number")
        except EmptyPage:
            raise Http404("Empty page") 


        for ed in page.object_list:
            return_json['results'].append( serialize_edition(ed) )

        if page.has_next():
            parseResult = urlparse.urlparse(request.build_absolute_uri(''))
            qd = QueryDict(parseResult.query).copy()
            qd['page'] = int(request_page) + 1
            query = qd.urlencode()
            return_json['next'] = urlparse.urlunsplit((parseResult.scheme, parseResult.netloc, parseResult.path, query, parseResult.fragment))
        else:
            return_json['next'] = None

        if page.has_previous():
            parseResult = urlparse.urlparse(request.build_absolute_uri(''))
            qd = QueryDict(parseResult.query).copy()
            qd['page'] = int(request_page) - 1
            query = qd.urlencode()
            return_json['previous'] = urlparse.urlunsplit((parseResult.scheme, parseResult.netloc, parseResult.path, query, parseResult.fragment))
        else:
            return_json['previous'] = None


        return Response(return_json)
Пример #22
0
def team_list(request, page=1):
    page = int(page)
    context = cache.get('team_list_{}'.format(page))
    if not context:
        p = Paginator(Team.objects.filter(detection__visible=True).annotate(detection_count=Count('detection')).exclude(
            name__isnull=True).exclude(name__exact='').order_by('-detection_count'), 20).page(page)
        context = {
            'has_next': p.has_next(),
            'has_previous': p.has_previous(),
            'page_number': page,
            'teams': [{
                'name': t.name,
                'user_count': t.user_set.count(),
                'detection_count': t.detection_count,
            } for t in p.object_list],
        }
        cache.set('team_list_{}'.format(page), context)
    return render(request, 'credoweb/team_list.html', context)
Пример #23
0
def get_user_detections_page(user, page):
    data = cache.get('user_{}_recent_detections_{}'.format(user.id, page))
    if not data:
        p = Paginator(Detection.objects.filter(user=user).order_by('-timestamp').filter(visible=True), 20).page(page)
        data = {
            'has_next': p.has_next(),
            'has_previous': p.has_previous(),
            'page_number': page,
            'detections': [{
                'date': format_date(d.timestamp),
                'timestamp': d.timestamp,
                'img': base64.encodebytes(d.frame_content).decode(),
                'x': d.x,
                'y': d.y
            } for d in p.object_list]
        }
        cache.set('user_{}_recent_detections_{}'.format(user.id, page), data)
    return data
Пример #24
0
def user_list(request, page=1):
    page = int(page)
    context = cache.get('user_list_{}'.format(page))
    if not context:
        p = Paginator(
            User.objects.filter(detection__visible=True).annotate(detection_count=Count('detection')).order_by(
                '-detection_count'), 20).page(page)
        context = {
            'has_next': p.has_next(),
            'has_previous': p.has_previous(),
            'page_number': page,
            'users': [{
                'name': u.username,
                'display_name': u.display_name,
                'detection_count': u.detection_count
            } for u in p.object_list],
        }
        cache.set('user_list_{}'.format(page), context)
    return render(request, 'credoweb/user_list.html', context)
Пример #25
0
def detection_list(request, page=1):
    try:
        page = int(page)
    except ValueError:
        raise Http404("Page index must be a number")

    context = cache.get("detection_list_{}".format(page))

    if not context:
        try:
            p = Paginator(
                Detection.objects.order_by("-timestamp").filter(
                    visible=True).only("timestamp", "frame_content", "x", "y",
                                       "user", "team"),
                20,
            ).page(page)
        except EmptyPage:
            raise Http404("Detection list page not found")

        context = {
            "has_next":
            p.has_next(),
            "has_previous":
            p.has_previous(),
            "page_number":
            page,
            "detections": [{
                "date": format_date(d.timestamp),
                "timestamp": d.timestamp,
                "x": d.x,
                "y": d.y,
                "user": {
                    "name": d.user.username,
                    "display_name": d.user.display_name,
                },
                "team": {
                    "name": d.team.name
                },
                "img": base64.encodebytes(d.frame_content).decode(),
            } for d in p.object_list],
        }
        cache.set("detection_list_{}".format(page), context)
    return render(request, "credoweb/detection_list.html", context)
Пример #26
0
def get_posts_for(user,
                  page=1,
                  count_likes=False,
                  attach_senders=True,
                  attach_users_who_liked=False,
                  check_user=None):
    """
    Returns QuerySet which contains posts received by `user`.
    Params:
        page - number of page
        count_likes - adds `n_likes` and `n_dislikes` fields to each post
        attach_sender - adds `sender` field to each post
        attach_users_who_liked - adds `users_who_liked` and `users_who_disliked`
                                 fields to each post
        check_user - accepts User object and adds `is_liked` and `is_disliked`
                     fields to each post, they represent if this post was liked
                     or disliked by user `check_user`
    """
    posts = user.received_posts.order_by('-date', '-time')
    try:
        posts_page = Paginator(posts, per_page=10).page(page)
    except InvalidPage:
        raise Http404(f'Posts page `{page}` does not exists.')
    posts = posts_page.object_list

    if attach_senders:
        posts = posts.select_related('sender')
    if attach_users_who_liked:
        posts = posts.prefetch_related('users_who_liked', 'users_who_disliked')
    if count_likes:
        posts = posts.annotate(n_likes=Count('users_who_liked'),
                               n_dislikes=Count('users_who_disliked'))
    if isinstance(check_user, get_user_model()):
        posts = posts.annotate(
            is_liked=Count('users_who_liked',
                           filter=Q(users_who_liked=check_user)),
            is_disliked=Count('users_who_disliked',
                              filter=Q(users_who_disliked=check_user)))
    # Monkey patching fields on QuerySet have to be done
    # after all calls modifications of QuerySet, otherwise
    # monkey patched field will disappear
    posts.next_page_num = (page + 1) if posts_page.has_next() else None
    return posts
Пример #27
0
def get_galleries(request, st_yr, st_mnth, end_yr, 
                        end_mnth, tags, page=None):
    """
    Returns some JSON corresponding to a list of image galleries and images.
    """
    
    IMG_GALS_PER_REQ = 5
    
    tags = [tag.strip() for tag in tags.split(',')]
    st_yr, st_mnth, end_yr, end_mnth = \
        int(st_yr), int(st_mnth), int(end_yr), int(end_mnth)
    end_yr, end_mnth = (end_yr+1, 1) if end_mnth > 11 else (end_yr, end_mnth+1)
    page = int(page or 1)
    
    q = Q(created_on__range=(
        datetime(st_yr, st_mnth, 1),
        datetime(end_yr, end_mnth, 1),
    ))
    for tag in tags:
        q = q & Q(tags__text=tag)
    # TODO: loading all the objects at once is REALLY inefficient; fix it
    imgs = list(Image.objects.filter(q)) + list(Gallery.objects.filter(q))
    p = Paginator(imgs, IMG_GALS_PER_REQ).page(page)
    
    galleries = {}
    for obj in p.object_list:
        if obj.__class__ == Gallery:
            galleries['gal_%d' % obj.pk] = render_to_string('image_gal_fragment.html', {
                'images': obj.images.all()[:MAX_IMGS_PER_GAL],
                'more': max(obj.images.count() - MAX_IMGS_PER_GAL, 0),
                'gal': obj})
        else:
            galleries['img_%d' % obj.pk] = render_to_string('image_gal_fragment.html', {
                'image': obj,
            })
    
    json_dict = {}
    json_dict['galleries'] = galleries
    json_dict['next_page'] = p.next_page_number() if p.has_next() else 0
    json_dict['prev_page'] = p.previous_page_number() if p.has_previous() else 0
    
    return HttpResponse(simplejson.dumps(json_dict))
Пример #28
0
 def get(self, request):
     if request.is_ajax():
         page_num = request.GET['page']
         page = Paginator(self.articles,
                          settings.NEWS_PER_PAGE).get_page(page_num)
         object_list = list(page.object_list)
         return JsonResponse({
             'data': object_list,
             'has_next': page.has_next()
         })
     else:
         articles = Paginator(
             self.articles, settings.NEWS_PER_PAGE).get_page(1).object_list
         return render(request,
                       template_name='news/index.html',
                       context={
                           'categories': self.categories,
                           'articles': articles,
                           **self.addition_context_data
                       })
Пример #29
0
def paginate(data,
             page=None,
             limit=None,
             url='',
             serializer=None,
             serializer_kwargs=None):
    next_page_url, previous_page_url, next_page, previous_page, count, pages = None, None, None, None, 0, 0
    page = int(page) if page else 1
    limit = int(limit) if limit else 10
    try:
        data = Paginator(data, limit)
        pages = data.num_pages
        count = data.count
        data = data.page(page)
        if data.has_next():
            next_page_url = '{}&page={}&limit={}'.format(url, page + 1, limit)
            next_page = page + 1
        if data.has_previous():
            previous_page_url = '{}&page={}&limit={}'.format(
                url, page - 1, limit)
            previous_page = page - 1
        if serializer:
            serializer_kwargs = serializer_kwargs if serializer_kwargs else {}
            data = serializer(data, many=True, **serializer_kwargs).data
        else:
            data = list(data)
    except EmptyPage or InvalidPage:
        data = []
    return {
        'data': data,
        'pagination': {
            'count': count,
            'pages': pages,
            'page': page,
            'limit': limit,
            'next': next_page,
            'next_url': next_page_url,
            'previous': previous_page,
            'previous_url': previous_page_url
        }
    }
Пример #30
0
    def get(self, request, username):
        req_user = User.objects.get(username=username)
        try:
            a = Answer.objects.filter(
                writer_id=req_user.id).order_by('time_written')
            if self.request.user != req_user:
                a = a.exclude(anonymous=True)
        except Answer.DoesNotExist:
            a = None
        p = Paginator(a, 3)
        p = p.page(request.GET.get('page'))

        if p.has_next():
            next_page = None
        else:
            next_page = 1

        return render_to_response('answers/answer_item.html', {
            'answers': p,
            'request': request,
            'next_page': next_page
        })
Пример #31
0
def make_pagination_ui_ctx(page: Paginator) -> Dict[str, Any]:
    """ Computes the layout of the pagination UI element """
    context = {}

    # 1 ... p c n ... l
    p = page.has_previous() and page.previous_page_number()
    c = page.number
    n = page.has_next() and page.next_page_number()
    l = page.paginator.num_pages

    # Start figuring out if we need the one and the dots
    if not p or p == 1:
        print1 = False
        print1Dots = False
    elif p == 2:
        print1 = True
        print1Dots = False
    else:
        print1 = True
        print1Dots = True

    context['print1'] = print1
    context['print1Dots'] = print1Dots

    # End by figuring out if we need the last tods etc
    if not n or n == l:
        printL = False
        printLDots = False
    elif n == l - 1:
        printL = True
        printLDots = False
    else:
        printL = True
        printLDots = True

    context['printL'] = printL
    context['printLDots'] = printLDots

    return context
Пример #32
0
def get_form(request):
    search_query = request.GET.get('search', '')
    if search_query:
        posts = Post.objects.filter(
            Q(title__icontains=search_query) | Q(body__icontains=search_query))
    else:
        posts = Post.objects.all()
    page = Paginator(posts, 2).get_page(request.GET.get('page', 1))

    is_paginated = page.has_other_pages()
    prev_page_num = '?page={}'.format(
        page.previous_page_number()) if page.has_previous() else ''
    next_page_num = '?page={}'.format(
        page.next_page_number()) if page.has_next() else ''

    context = {
        'page': page,
        'is_paginated': is_paginated,
        'next_page': next_page_num,
        'prev_page': prev_page_num
    }
    return render(request, 'blog/index.html', context=context)
Пример #33
0
def truncated_page_range(page: int, paginator: Paginator):
    num_pages = paginator.paginator.num_pages
    if not paginator.has_previous() or page <= 4:
        for i in range(1, 7):
            yield i
        yield '..'
        yield num_pages
        return

    if not paginator.has_next() or page > num_pages - 4:
        yield 1
        yield '..'
        for i in range(num_pages - 4, num_pages):
            yield i
        return

    yield 1
    yield '..'
    for i in range(page - 3, page + 4):
        yield i

    yield '..'
    yield num_pages
Пример #34
0
def list_users(world_id, page, page_size, search_term) -> object:
    qs = User.objects.filter(world_id=world_id)
    if search_term:
        qs = qs.filter(profile__display_name__icontains=search_term)

    try:
        p = Paginator(qs.order_by("id").values("id", "profile"),
                      page_size).page(page)
        return {
            "results": [
                dict(
                    id=str(u["id"]),
                    profile=u["profile"],
                ) for u in p.object_list
            ],
            "isLastPage":
            not p.has_next(),
        }
    except InvalidPage:
        return {
            "results": [],
            "isLastPage": True,
        }
Пример #35
0
def attempt_question(request, quiz_id, attempt_id, question_id):
  """ opens the selected question in the quiz-attempt mode. """
  quiz = get_object_or_404(Quiz, id=quiz_id, published=True)
  questions = quiz.quiz_questions.order_by('number')
  questions_prev_next = Paginator(questions, 1).page(question_id)
  
  """ @todo, this is buggy and needs to be fixed. """
  question = get_object_or_404(Question, quiz=quiz_id, number=question_id)
  answers = Answer.objects.filter(question=question)
  attempt_question_form = AttemptQuestionForm(instance=question)
  
  if request.method == "POST":
    attempt = Attempt.objects.get(owner=request.user, quiz=quiz_id, attempt=attempt_id)
    attempt_question, created = AttemptQuestion.objects.get_or_create(attempt=attempt, question=question)
    attempt_question_form = AttemptQuestionForm(request.POST, instance=attempt_question)
    
    if attempt_question_form.is_valid():
      answer_form = attempt_question_form.save(commit=False)
      answer_form.save()
      
      if questions_prev_next.has_next():
        return HttpResponseRedirect(reverse("quizattempt.views.attempt_question", args=[quiz_id, attempt.attempt, questions_prev_next.next_page_number()]))
      else:
        attempt.status = "complete"
        attempt.save()
        return HttpResponseRedirect(reverse("reports.views.report_attempt", args=[quiz_id, attempt.attempt]))
        
  return render_to_response("quizattempt/attempt_question.html", {
              "quiz_id" : quiz_id,
              "attempt_id" : attempt_id,
              "selected_question": question,
              "questions_prev_next" : questions_prev_next,
              "questions" : questions,
              "answers": answers,
              "attemptanswer_form" : attempt_question_form,
              "pagetitle" : "Attempt Question",
          }, context_instance=RequestContext(request))
Пример #36
0
def paginate(items, query):
    response = {}
    page_number = query.get('page', 1)
    per_page = query.get('per_page', CatalogueConfig.get_solo().items_per_page)
    ordering = query.get('sort', '-created')
    if not item_settings.PAGINATE_AJAX:
        page = items
    else:
        page = Paginator(items, per_page=per_page).get_page(page_number)
        is_paginated = page.has_other_pages()
        current_page = page.number
        last_page = page.paginator.num_pages
        page_range = page.paginator.page_range
        has_prev = page.has_previous()
        has_next = page.has_next()
        next_url = f'?page={page.next_page_number()}' if has_next else ''
        prev_url = f'?page={page.previous_page_number()}' if has_prev else ''
        first_url = f'?page=1'
        last_url = f'?page={last_page}'
        response.update({
            'is_paginated': is_paginated,
            'current_page': current_page,
            'page_range': list(page_range),
            'last_page': last_page,
            'first_url': first_url,
            'next_url': next_url,
            'prev_url': prev_url,
            'last_url': last_url,
            'has_prev': has_prev,
            'has_next': has_next,
        })

    page_items = ItemDetailSerializer(page, many=True, read_only=True).data
    response = {
        'paginated_items': page_items,
    }
    return response
Пример #37
0
def detection_list(request, page=1):
    page = int(page)
    context = cache.get('detection_list{}'.format(page))
    if not context:
        p = Paginator(
            Detection.objects.order_by('-timestamp').filter(visible=True).select_related('user', 'team'), 20).page(page)
        context = {
            'has_next': p.has_next(),
            'has_previous': p.has_previous(),
            'page_number': page,
            'detections': [{
                'date': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(d.timestamp / 1000)),
                'user': {
                    'name': d.user.username,
                    'display_name': d.user.display_name,
                },
                'team': {
                    'name': d.team.name,
                },
                'img': base64.encodestring(d.frame_content)
            } for d in p.object_list],
        }
        cache.set('detection_list{}'.format(page), context)
    return render(request, 'credoweb/detection_list.html', context)
Пример #38
0
def select_paper_all(args):
    """Get All Papers"""

    page_number = 1 if constants.PAGE_NUMBER not in args else int(args[constants.PAGE_NUMBER])

    # list of tuple (id, abtract, DOI)
    paper_queryset = Paper.objects.all().values_list('id', 'abstract', 'DOI')

    papers = Paginator(paper_queryset, ALL_PAPER_PAGE_COUNT).get_page(page_number)

    is_finished = not papers.has_next()

    results = [] # list of dictionaries whose keys are ItemId, Abstract, and Keywords

    for paper in papers:
        result = {}
        paper_id, abstract, doi = paper
        keywords = paper_utils.get_keywords_paper(Q(paper_id=paper_id))
        result['Keywords'] = keywords[paper_id] if paper_id in keywords else []
        result['ItemId'] = paper_id

        if abstract:
            result['Abstract'] = abstract
        # If abstract doesn't exist, try getting abstract this time.
        #   We can use 'alternative-id' of Crossref for getting results from Semantic Scholar,
        #   but it is currently not saved in our DB. So use only DOI for now.
        else:
            if doi:
                __exploit_semanticscholar_for_abstract(paper_id, [doi]) # NOTE: This doesn't use shared_task of celery
                result['Abstract'] = Paper.objects.get(id=paper_id).abstract
            else:
                result['Abstract'] = abstract # save empty abstract

        results.append(result)

    return results, page_number, is_finished
Пример #39
0
 def get_results(self, request, term, page, context):
     queryset = ContestProfile.objects.filter(Q(user__user__username__icontains=term) | Q(user__name__icontains=term))\
                              .select_related('user__user')
     page = Paginator(queryset, 20).page(page)
     return 'nil', page.has_next(), [(profile.id, 'Contest: ' + profile.user.long_display_name) for profile in page]
def community(request):
    """A view to render the community page, including makeGroup form."""
    if request.user.is_authenticated and hasattr(request.user, 'userprofile'):
        template = "community/community.html"
        # Get groups if user is a member and group is shared or if user is admin.
        groups1 = CustomGroup.objects.filter(group_users=request.user).filter(
            share=True).exclude(users_delete=request.user)
        groups2 = CustomGroup.objects.filter(admin=request.user).exclude(
            users_delete=request.user)
        groups = groups1.union(groups2)
        age_group = getAgeGroup(request)
        selected_group = getGroupSelectionUsers(request)
        selected_group_logs = getGroupSelection(request)
        selected_group = selected_group.order_by("-herolevels__general_level")
        group = Paginator(selected_group, 25)
        group = group.page(1)
        # Get selected group stats
        members = selected_group.count()
        male = selected_group.filter(userprofile__gender="M").count()
        female = selected_group.filter(userprofile__gender="F").count()
        date_month = date.today() - timedelta(days=30)
        month = selected_group_logs.filter(date__gte=date_month).count()
        admin = False
        group_s = getGroup(request)
        groupname = ''
        if group_s["custom"] != "false":
            c_group = CustomGroup.objects.get(pk=group_s["custom"])
            groupname = c_group.name
            admin = c_group.admin
        else:
            if group_s["location"] == "group-city":
                groupname = request.user.userprofile.town_or_city
            elif group_s["location"] == "group-country":
                groupname = request.user.userprofile.get_country_display()
            else:
                groupname = "global"
            if group_s["age"] == "true":
                groupname = str(groupname) + ' ' + age_group.split(' ')[0]
        average_user = round(month / members)
        average_l = selected_group.aggregate(Avg('herolevels__general_level'))
        average_level = round(average_l['herolevels__general_level__avg'])
        form = CustomGroupForm()
        context = {
            'form': form,
            'groupname': groupname,
            'admin': admin,
            'groups': groups,
            'age_group': age_group,
            'group': group,
            'has_next': group.has_next(),
            'members': members,
            'male': male,
            'female': female,
            'month': month,
            'average_user': average_user,
            'average_level': average_level
        }
        return render(request, template, context)
    elif not request.user.is_authenticated:
        return render(request, 'home/index.html')
    else:
        return redirect(reverse('create_profile'))
Пример #41
0
 def get_results(self, request, term, page, context):
     queryset = Organization.objects.filter(
         Q(key__icontains=term) | Q(name__icontains=term))
     page = Paginator(queryset, 20).page(page)
     return 'nil', page.has_next(), [(org.id, org.name) for org in page]
Пример #42
0
 def get_results(self, request, term, page, context):
     queryset = Organization.objects.filter(Q(key__icontains=term) | Q(name__icontains=term))
     page = Paginator(queryset, 20).page(page)
     return 'nil', page.has_next(), [(org.id, org.name) for org in page]
Пример #43
0
 def get_results(self, request, term, page, context):
     queryset = Comment.objects.filter(Q(title__icontains=term) | Q(page__icontains=term))
     page = Paginator(queryset, 20).page(page)
     return 'nil', page.has_next(), [(comment.id, '-' * comment.level + comment.title) for comment in page]