Example #1
0
def paginate_context(request, model, urlbase, object_list, page, **kwargs):
    '''
    Helper function to make standard pagination available for the template
    "snapboard/page_navigation.html"
    '''
    page = int(page)
    pindex = page
    page_next = None
    page_prev = None
    page_range = None

    paginator = Paginator(object_list, _userdata(request, 'tpp'))
    try:
        object_page = paginator.page(pindex)
    except InvalidPage:
        raise InvalidPage

    if object_page.has_next():
        page_next = page + 1
    if object_page.has_previous():
        page_prev = page - 1
    if paginator.num_pages > 2:
        page_range = range(1, paginator.num_pages+1)

    return {
            'page': page,
            'page_total': paginator.num_pages,
            'page_next': page_next,
            'page_prev': page_prev,
            'page_range': page_range,
            model.__name__.lower() + '_page': object_page.object_list,
            'page_nav_urlbase': urlbase,
        }
Example #2
0
def view_groups(request):
    """
    Django View. List all groups.

    @type request: C{django.http.HttpRequest}
    @param request: Client Request object
    """

    groups_list = models.BookiGroup.objects.all().extra(select={'lower_name': 'lower(name)'}).order_by('lower_name')

    paginator = Paginator(groups_list, 50) 

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

    try:
        groups = paginator.page(page)
    except (EmptyPage, InvalidPage):
        groups = paginator.page(paginator.num_pages)

    return render_to_response('portal/groups.html', {"request": request, 
                                                     "title": "Booki groups", 
                                                     "groups": groups })
Example #3
0
    def build_page(self):
        """
        Paginates the results appropriately.

        In case someone does not want to use Django's built-in pagination, it
        should be a simple matter to override this method to do what they would
        like.
        """
        try:
            page_no = int(self.request.GET.get('page', 1))
        except (TypeError, ValueError):
            raise Http404("Not a valid number for page.")

        if page_no < 1:
            raise Http404("Pages should be 1 or greater.")

        start_offset = (page_no - 1) * self.results_per_page
        self.results[start_offset:start_offset + self.results_per_page]

        paginator = Paginator(self.results, self.results_per_page)

        try:
            page = paginator.page(page_no)
        except InvalidPage:
            raise Http404("No such page!")

        return (paginator, page)
Example #4
0
def user_list(request):
    context = RequestContext(request)

    if request.method == 'POST':
        form = forms.FindUserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            try:
                user = models.User.objects.get(username=username)
                return redirect('kegadmin-edit-user', user.id)
            except models.User.DoesNotExist:
                messages.error(request, 'User "%s" does not exist.' % username)

    users = models.User.objects.exclude(username='guest').order_by('-id')
    paginator = Paginator(users, 25)

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

    context['users'] = users
    return render_to_response('kegadmin/user_list.html', context_instance=context)
Example #5
0
def visual_index(request, **kwargs):

    all_neurons, search_form = get_form_and_neurons( request,
                                                     kwargs['project_id'],
                                                     kwargs )

    # From: http://docs.djangoproject.com/en/1.0/topics/pagination/
    paginator = Paginator(all_neurons, 5)
    if 'page' in kwargs:
        page = kwargs['page'] or 1
    else:
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        neurons = paginator.page(page)
    except (EmptyPage, InvalidPage):
        neurons = paginator.page(paginator.num_pages)

    return my_render_to_response(request,
                                 'vncbrowser/visual_index.html',
                                 {'sorted_neurons': neurons.object_list,
                                  'sorted_neurons_page' : neurons,
                                  'project_id': kwargs['project_id'],
                                  'catmaid_url': settings.CATMAID_URL,
                                  'user': kwargs['logged_in_user'],
                                  'search_form': search_form })
Example #6
0
def show_chat(request,to):
    from_user = request.user
    to_user = get_object_or_404(User,username=to)
    if from_user==to_user:
        messages.error(request,_(u'Вы не можете написать сообщение самому себе'))
#        messages.error(request,_(u'Can not write email to yourself'))
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    #get existed chat
    chat= Chat.objects.filter(from_user=from_user,to_user=to_user) or Chat.objects.filter(to_user=from_user,from_user=to_user)
    if chat:
        chat=chat[0]

    msgs=None
    if chat:
        if chat.from_user==from_user:
            chat.is_from_user_read=False
        else:
            chat.is_to_user_read=False
        chat.save()
        msgs= chat.comments.all()
        msgs=Paginator(msgs,10)
        try:
            page = request.GET['page']
        except:
            page = 1

        try:
            msgs = msgs.page(page)
        except (EmptyPage, InvalidPage):
            msgs = msgs.page(msgs.num_pages)

    return render_to_response('cart/message.html',{'chat':chat,'msgs':msgs,'to':to},context_instance=RequestContext(request))
Example #7
0
def story_page(request, story_id, story_slug):
    """
    A page or part of story.
    @story_id
    @story_slug
    """
    user = request.user
    all_parts = Part.objects.filter(story = story_id).order_by('order')
    paginator = Paginator(all_parts, 1)
    page = request.GET.get('page')
    story = Story.objects.get(id = story_id)
    
    # If the slug is wrong, redirect to the correct url
    story_slug_db = story.slug
    if story_slug_db != story_slug:
        url = "/story/" + str(story.id) + "/" + str(story_slug_db) + "/"
        return HttpResponseRedirect(url)
    
    try:
        parts = paginator.page(page)
    except (PageNotAnInteger, TypeError):
        parts = paginator.page(1)
    except EmptyPage:
        parts = paginator.page(paginator.num_pages)
    
    c = {"parts": parts,
	"story":story,
         "user": user,}
    return render_to_response('book.html', c, context_instance = RequestContext(request))
	def post(self,page=1):
		searchText = self.request.get('searchtext')	
		try:
			page = int(page)
		except:
			page = 1
		courses = Course.all()
		allcourses = []
		for course in courses:
			if searchText in course.tags:
				course.tagstring = GetCourseTags(course.courseid)
				course.creatoremail = GetUserEmailFromGuser(course.createdbyuser)
				course.usercanreg = UserCanRegister(users.get_current_user().user_id(), course.courseid)
				course.regcount = GetCourseRegCount(course.courseid)
				allcourses.append(course)

		paginator = Paginator(allcourses,3)
		#if page>=paginator:
		#	page = paginator

		self.template_values = {
            "courses" : paginator.page(page).object_list
            ,"pages" : paginator.page_range
            ,"page" : page
		}

		page_display(self,"templates/coursesearch.html")
Example #9
0
def photo_review(request, instance):
    page_number = int(request.REQUEST.get('page', '1'))
    sort_order = request.REQUEST.get('sort', '-created_at')
    is_archived = request.REQUEST.get('archived', 'False') == 'True'

    photos = get_photos(instance, sort_order, is_archived)
    paginator = Paginator(photos, _PHOTO_PAGE_SIZE)

    try:
        paged_photos = paginator.page(page_number)
    except EmptyPage:
        # If the page number is out of bounds, return the last page
        paged_photos = paginator.page(paginator.num_pages)

    urlizer = UrlParams('photo_review', instance.url_name, page=page_number,
                        sort=sort_order, archived=is_archived)

    return {
        'photos': paged_photos,
        'sort_order': sort_order,
        'is_archived': is_archived,
        'is_archived_text': _("Archived") if is_archived else _("Active"),
        'is_archived_text_lower': (_("archived") if is_archived
                                   else _("active")),
        'url_for_pagination': urlizer.url('sort', 'archived'),
        'url_for_filter': urlizer.url('sort'),
        'url_for_sort': urlizer.url('archived'),
        'full_params': urlizer.params('page', 'sort', 'archived')
    }
Example #10
0
def SelfPaginator(request,List,Limit):
    '''分页模块,用法:
        1.view中引入:
        ex:from website.common.CommonPaginator import SelfPaginator
        
        2.SelfPaginator需要传入三个参数
            (1).request:获取请求数据
            (2).List:为需要分页的数据(一般为*.objects.all()取出来数据)
            (3).Limit:为每页显示的条数
        ex:lst = SelfPaginator(request,mList, 5)
        
        3.view需要获取SelfPaginator return的lst,并把lst返回给前端模板
        ex:kwvars = {'lPage':lst,}
        
        4.前端需要for循环lPage也就是lst读取每页内容
        ex:{% for i in lPage %} ... {% endfor %}
        
        5.模板页引入paginator.html
        ex:{% include "common/paginator.html" %}
    '''

    paginator = Paginator(List, int(Limit))

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

    return lst
Example #11
0
def list_projects(request):
    """
    A list of all projects in cloud teams
    """
    q = request.GET.get('q', '')
    qs = Project.objects.filter(Q(title__icontains=q) | Q(description__icontains=q) |
                                Q(category__icontains=q))

    # ordering
    order = request.GET.get('order', 'latest')
    if order == 'most-popular':
        qs = qs.annotate(num_followers=Count('followed')).order_by('-num_followers', '-created')
    else:
        order = 'latest'
        qs = qs.order_by('-created')

    pages = Paginator(qs, 10)

    context = {
        'n_of_projects': Project.objects.all().count(),
        'page_obj': pages.page(int(request.GET.get('page', '1'))),
        'q': q,
        'order': order
    }

    return render(request, 'ct_projects/project/all.html', context)
def profile_search_id(request):

    queryset = profiles.objects.all().order_by('-timestamp')
    for object in queryset:
        if object.pId == "TMG":
            object.pId = "TMG00" + str(object.tmId)
            object.save()

    query = request.GET.get('pid')

    if query:
        instance = get_object_or_404(profiles,pId=str(query))
        return HttpResponseRedirect(instance.get_absolute_url())

    paginator = Paginator(queryset, 5)  # Show 5 contacts per page

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

    content = {
        "objectset": queryset1,
        "title": "list"
    }
    return render(request, "profile_search_id.html", content)
Example #13
0
def prereg(request):
    """Redirects to prereg page if user has prereg access
    :param request: Current logged in user
    :return: Redirect to prereg page with username, reviewers, and user obj
    """
    paginator = Paginator(get_prereg_drafts(user=request.user), 5)

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

    page = paginator.page(page_number)

    try:
        drafts = [serializers.serialize_draft_registration(d, json_safe=False) for d in page]
    except EmptyPage:
        drafts = []

    for draft in drafts:
        draft['form'] = DraftRegistrationForm(draft)

    context = {
        'drafts': drafts,
        'page': page,
        'IMMEDIATE': serializers.IMMEDIATE,
    }
    return render(request, 'pre_reg/prereg.html', context)
Example #14
0
def system_install_record(request):
    """
    List all operating system installation records
    """
    
    user = request.user 
    if request.method == 'POST':
        search_fields = request.POST.get('search')
    else:
        try:
            search_fields = request.GET.get('search','none')
        except ValueError:
            search_fields = 'none'
    if search_fields == 'none':
        record = InstallRecord.objects.all().order_by('-id')       
    else:
        record = InstallRecord.objects.filter(hostname__contains=search_fields).order_by('-id')   
    paginator = Paginator(record,12)

    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_to_response('install_record_list.html', {'record': record, 'page': page, 'paginator':paginator,'search':search_fields,'request':request},context_instance=RequestContext(request))
Example #15
0
def adminInsumoDetail(request, insumo):
	insumo = get_object_or_404(Insumo, pk = insumo) 
	entradas = Entrada.objects.filter(insumo=insumo)
	salidas = Salida.objects.filter(insumo=insumo)
	template =  get_template("admininsumodetail.html")
	sort = request.GET.get('o') #orden del query filter
	if sort == None: #si no hay orden en URL se refiere a -fecha 
		sort = '-fecha'
	filters = EntradasFilter(request.GET, queryset=Entrada.objects.filter(insumo=insumo))
	paginator = Paginator(filters, 10)
	page = request.GET.get('page')
	try:
		entradas= paginator.page(page)
	except PageNotAnInteger:
        # Si la pagina no es un entero muestra la primera pagina
		entradas = paginator.page(1)
	except EmptyPage:
        # si la pagina esta fuera de rango, muestra la ultima pagina
		entradas = paginator.page(paginator.num_pages)


	context = {
        'insumo': insumo, 'entradas': entradas,'filters': filters,'sort':sort,
    }
	return HttpResponse(template.render(context, request))
Example #16
0
def make_pages(form, page):
    paginator = Paginator(form, 10)
    try:
        form = paginator.page(page)
    except PageNotAnInteger:
        form = paginator.page(1)
    except EmptyPage:
        form = paginator.page(paginator.num_pages)
    
    for d in form: 
        try:
            docdata = MetaData.objects.get(link=d.url)
            reviewed = docdata.reviewed
            if reviewed == True:
                reviewed_true.append(str(docdata.link))
                
            processed = docdata.processed
            if processed == True:
                processed_true.append(str(docdata.link))

            notes[d.url] = docdata.notes
            
        except MetaData.DoesNotExist:
            continue
    
    for d in form:  
        try:
            debug(Registrant.objects.get(reg_id=int(d.reg_id)))
            reg = Registrant.objects.get(reg_id=d.reg_id)
            names[d.reg_id] = reg.reg_name
        except Registrant.DoesNotExist:
            continue
    
    return form 
Example #17
0
    def get_results(self, request):
        if not SEARCH_VAR in request.GET:
            return super(SearchChangeList, self).get_results(request)

        # Note that pagination is 0-based, not 1-based.
        sqs = SearchQuerySet().models(self.model).auto_query(request.GET[SEARCH_VAR]).load_all()

        paginator = Paginator(sqs, self.list_per_page)
        # Get the number of objects, with admin filters applied.
        result_count = paginator.count
        full_result_count = SearchQuerySet().models(self.model).all().count()

        can_show_all = result_count <= list_max_show_all(self)
        multi_page = result_count > self.list_per_page

        # Get the list of objects to display on this page.
        try:
            result_list = paginator.page(self.page_num+1).object_list
            # Grab just the Django models, since that's what everything else is
            # expecting.
            result_list = [result.object for result in result_list]
        except InvalidPage:
            result_list = ()

        self.result_count = result_count
        self.full_result_count = full_result_count
        self.result_list = result_list
        self.can_show_all = can_show_all
        self.multi_page = multi_page
        self.paginator = paginator
Example #18
0
    def test_page_getitem(self):
        """
        Tests proper behavior of a paginator page __getitem__ (queryset
        evaluation, slicing, exception raised).
        """
        paginator = Paginator(Article.objects.order_by('id'), 5)
        p = paginator.page(1)

        # Make sure object_list queryset is not evaluated by an invalid __getitem__ call.
        # (this happens from the template engine when using eg: {% page_obj.has_previous %})
        self.assertIsNone(p.object_list._result_cache)
        with self.assertRaises(TypeError):
            p['has_previous']
        self.assertIsNone(p.object_list._result_cache)
        self.assertNotIsInstance(p.object_list, list)

        # Make sure slicing the Page object with numbers and slice objects work.
        self.assertEqual(p[0], Article.objects.get(headline='Article 1'))
        self.assertQuerysetEqual(p[slice(2)], [
            "<Article: Article 1>",
            "<Article: Article 2>",
        ]
        )
        # After __getitem__ is called, object_list is a list
        self.assertIsInstance(p.object_list, list)
Example #19
0
def dashboard(request):
    if request.user.is_authenticated():
        try:
            me = UserProfile.objects.get(user=request.user)
        except UserProfile.DoesNotExist:
            display_name = request.user
            return redirect('/register/')
    neos = Neo.objects.all().extra(
           select={
               'display_name': 'SELECT display_name FROM neo_userprofile WHERE neo_userprofile.id = neo_neo.user_id'
           },
        )

    paginator = Paginator(neos, 50)
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    # If page request (9999) is out of range, deliver last page of results.
    try:
        neo_list = paginator.page(page)
    except (EmptyPage, InvalidPage):
        neo_list = paginator.page(paginator.num_pages)

    if request.user.is_authenticated():
        return render(request, 'dashboard.html', {'neo_list': neo_list, 'page': page, 'me': me})
    return render(request, 'dashboard.html', {'neo_list': neo_list, 'page': page})
Example #20
0
    def index(self, page=1):
        # prepare result
        result = self.get_default_result("genres", page)

        object_list = Genre.objects.all()
        object_list = self.source_set_order(object_list)

        # get data
        paginator = Paginator(object_list, self.count)
        try:
            page_obj = paginator.page(page)
        except InvalidPage:
            return result

        result = self.result_set_order(result)
        result["hasNextPage"] = page_obj.has_next()
        for item in page_obj.object_list:
            dataset = {
                "id": item.id,
                "genre": item.Name,
            }

            result["itemList"].append(dataset)

        return result
Example #21
0
def get_paginator(objects, page, limit):
    """
    Create and return a Paginator filled with the objects and paginated
    at the given page.

    Args:
        ``objects`` (list): A list of objects to be paginated.

        ``page`` (int): The current page of the pagination. If it is not
        a valid integer, the first page is used. If the page provided is
        bigger than the nuber of pages available, the last page is
        returned.

        ``limit`` (int): The number of items per page.

    Returns:
        ``django.core.paginator.Page``. The paginated data.

        ``django.core.paginator.Paginator``. The Paginator object.
    """
    paginator = Paginator(objects, limit)
    try:
        paginated = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        paginated = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        paginated = paginator.page(paginator.num_pages)
    return paginated, paginator
Example #22
0
    def index(self, page=1):
        # prepare result
        result = self.get_default_result("years", page)

        object_list = Song.objects.values("Year").distinct()
        object_list = object_list.exclude(Year=None).exclude(Year=0)
        object_list = self.source_set_order(object_list)

        # get data
        paginator = Paginator(object_list, self.count)
        try:
            page_obj = paginator.page(page)
        except InvalidPage:
            return result

        result = self.result_set_order(result)
        result["hasNextPage"] = page_obj.has_next()
        for item in page_obj.object_list:
            dataset = {
                "year": item["Year"],
            }

            result["itemList"].append(dataset)

        return result
Example #23
0
    def paginate_items(self, items, page):
        """
        Paginate the list of items, if needed.
        """
        paginate_by = self.get_paginate_by(items)
        allow_empty = self.get_allow_empty()
        if not paginate_by:
            if not allow_empty and len(items) == 0:
                raise Http404("Empty list and '%s.allow_empty' is False." % self.__class__.__name__)
            return (None, None, items)

        paginator = Paginator(items, paginate_by, allow_empty_first_page=allow_empty)
        page = page or self.request.GET.get('page', 1)
        try:
            page_number = int(page)
        except ValueError:
            if page == 'last':
                page_number = paginator.num_pages
            else:
                raise Http404("Page is not 'last', nor can it be converted to an int.")
        try:
            page = paginator.page(page_number)
            return (paginator, page, page.object_list)
        except InvalidPage:
            raise Http404('Invalid page (%s)' % page_number)
Example #24
0
 def get_context_data(self):
     paginator = Paginator(newest_posts(), 100)
     try:
         p = paginator.page(self.request.GET.get('page', '1'))
     except PageNotAnInteger:
         p = paginator.page('1')
     return dict(posts=p.object_list, paginator=p)
Example #25
0
    def post(self, request, *args, **kwargs):
        template_name = "drinkersList.html"
        http_method_names = ['get', 'post']
        user = self.request.user
        models = locateDrinkers
        form = forms.LocateDrinkersForm(request.POST)
        if form.is_valid():
          # The form is valid and can be saved to the database
          # by calling the 'save()' method of the ModelForm instance.
          searchAttributes = form.save(commit=False)
          print "searchAttributes.boozshopaddress", searchAttributes.boozshopaddress
          #searchResults = boozProfiles.objects.filter(Booz_shop_location__icontains=searchAttributes.boozshopaddress)
          searchResults = boozProfiles.objects.all()
          paginator = Paginator(searchResults, 25) # Show 25 contacts per page
          page = request.GET.get('page')
          print "searchResults.query", searchResults.query
          print "searchResults::" ,str(searchResults)
          try:
              profilePerPages = paginator.page(page)
          except PageNotAnInteger:
              profilePerPages = paginator.page(1)
          except EmptyPage:
              profilePerPages = paginator.page(paginator.num_pages)

          return render_to_response("drinkersList.html", {"profilePerPages": profilePerPages})


          # This means that the request is a GET request. So we need to
          # create an instance of the TShirtRegistrationForm class and render it in
          # the template
        else:
            form = forms.LocateDrinkersForm(request.POST)
            return render(request, "locatedrinkers.html", { 'form' : form })
Example #26
0
def index(request, parent_page_id=None):
    if parent_page_id:
        parent_page = get_object_or_404(Page, id=parent_page_id)
    else:
        parent_page = Page.get_first_root_node()

    pages = parent_page.get_children().prefetch_related('content_type')

    # Get page ordering
    ordering = request.GET.get('ordering', '-latest_revision_created_at')
    if ordering not in ['title', '-title', 'content_type', '-content_type', 'live', '-live', 'latest_revision_created_at', '-latest_revision_created_at', 'ord']:
        ordering = '-latest_revision_created_at'

    # Pagination
    if ordering != 'ord':
        ordering_no_minus = ordering
        if ordering_no_minus.startswith('-'):
            ordering_no_minus = ordering[1:]
        pages = pages.order_by(ordering).annotate(null_position=Count(ordering_no_minus)).order_by('-null_position', ordering)

        p = request.GET.get('p', 1)
        paginator = Paginator(pages, 50)
        try:
            pages = paginator.page(p)
        except PageNotAnInteger:
            pages = paginator.page(1)
        except EmptyPage:
            pages = paginator.page(paginator.num_pages)

    return render(request, 'wagtailadmin/pages/index.html', {
        'parent_page': parent_page,
        'ordering': ordering,
        'pagination_query_params': "ordering=%s" % ordering,
        'pages': pages,
    })
Example #27
0
def _list(request, is_active, is_formal):
    potential_list = Potential.objects.filter(is_active=is_active, is_formal=is_formal)
    paginator = Paginator(potential_list, 6) # 6 records / per page

    page = request.GET.get('page') # pageNo

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

    list = []
    for potential in potentials:
        list.append(potential.tojson())

    response_data = {}
    response_data['potentials'] = list
    response_data['paginator.num_pages'] = potentials.paginator.num_pages
    response_data['number'] = potentials.number

    return response_data
Example #28
0
def content_type_use(request, content_type_app_name, content_type_model_name):
    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404

    p = request.GET.get("p", 1)

    page_class = content_type.model_class()

    # page_class must be a Page type and not some other random model
    if not issubclass(page_class, Page):
        raise Http404

    pages = page_class.objects.all()

    paginator = Paginator(pages, 10)

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

    return render(request, 'wagtailadmin/pages/content_type_use.html', {
        'pages': pages,
        'app_name': content_type_app_name,
        'content_type': content_type,
        'page_class': page_class,
    })
Example #29
0
def pagination():
    class BookTable(tables.Table):
        name = tables.Column()

    # create some sample data
    data = []
    for i in range(100):
        data.append({"name": "Book No. %d" % i})
    books = BookTable(data)

    # external paginator
    paginator = Paginator(books.rows, 10)
    assert paginator.num_pages == 10
    page = paginator.page(1)
    assert page.has_previous() is False
    assert page.has_next() is True

    # integrated paginator
    books.paginate(page=1)
    Assert(hasattr(books, "page")) is True

    books.paginate(page=1, per_page=10)
    Assert(len(list(books.page.object_list))) == 10

    # new attributes
    Assert(books.paginator.num_pages) == 10
    Assert(books.page.has_previous()) is False
    Assert(books.page.has_next()) is True

    # exceptions are converted into 404s
    with Assert.raises(Http404) as error:
        books.paginate(Paginator, page=9999, per_page=10)
        books.paginate(Paginator, page='abc', per_page=10)
Example #30
0
def _list_groups(request, template, query):
    """Lists groups from given query."""

    sort_form = SortForm(request.GET)
    show_pagination = False

    if sort_form.is_valid():
        query = query.order_by(sort_form.cleaned_data['sort'], 'name')
    else:
        query = query.order_by('name')

    paginator = Paginator(query, settings.ITEMS_PER_PAGE)

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

    if paginator.count > settings.ITEMS_PER_PAGE:
        show_pagination = True

    data = dict(groups=groups, page=page, sort_form=sort_form, show_pagination=show_pagination)
    return render(request, template, data)