本文整理汇总了Python中django.core.paginator.QuerySetPaginator类的典型用法代码示例。如果您正苦于以下问题:Python QuerySetPaginator类的具体用法?Python QuerySetPaginator怎么用?Python QuerySetPaginator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QuerySetPaginator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: list
def list(
self,
request,
queryset,
page=None,
):
"""
Renders a list of model objects to HttpResponse.
"""
if self.paginate_by:
paginator = QuerySetPaginator(queryset, self.paginate_by)
if not page:
page = request.GET.get('page', 1)
try:
page = int(page)
object_list = paginator.page(page).object_list
except (InvalidPage, ValueError):
if page == 1 and self.allow_empty:
object_list = []
else:
return self.error(request, 404)
else:
object_list = list(queryset)
return HttpResponse(self.render(object_list), self.mimetype)
示例2: series_and_issue
def series_and_issue(request, series_name, issue_nr, sort=ORDER_ALPHA):
""" Looks for issue_nr in series_name """
things = Issue.objects.filter(series__name__exact = series_name) \
.filter(number__exact = issue_nr)
if things.count() == 1: # if one display the issue
return HttpResponseRedirect(urlresolvers.reverse(issue,
kwargs={ 'issue_id': things[0].id }))
else: # if more or none use issue_list.html from search
p = QuerySetPaginator(things, 100)
page_num = 1
if (request.GET.has_key('page')):
page_num = int(request.GET['page'])
page = p.page(page_num)
context = {
'items' : things,
'item_name' : 'issue',
'plural_suffix' : 's',
'heading' : series_name + ' #' + issue_nr,
'style' : 'default',
}
if 'style' in request.GET:
context['style'] = request.GET['style']
return paginate_response(
request, things, 'gcd/search/issue_list.html', context)
示例3: detail
def detail(request, context):
""" Custom object detail function that adds a QuestionForm to the context. """
interview = context['object']
page_no = get_page_no(request)
qset = interview.get_questions()
paginator = QuerySetPaginator(qset, INTERVIEW_PAGINATION_PER_PAGE)
if page_no > paginator.num_pages or page_no < 1:
raise Http404
page = paginator.page(page_no)
interviewees = interview.get_interviewees(request.user)
context.update({
'interviewees': interviewees,
'is_paginated': paginator.num_pages > 1,
'results_per_page': INTERVIEW_PAGINATION_PER_PAGE,
'page': page,
'form' : QuestionForm(request=request),
'questions' : page.object_list,
})
return render_to_response(
get_templates_from_placement('object.html', context['placement']),
context,
context_instance=RequestContext(request)
)
示例4: paginate_queryset_for_request
def paginate_queryset_for_request(request, qset, paginate_by):
""" returns appropriate page for view. Page number should
be set in GET variable 'p', if not set first page is returned.
"""
item_number_mapping = {}
for i, c in enumerate(qset):
item_number_mapping[c._get_pk_val()] = i + 1
paginator = QuerySetPaginator(qset, paginate_by)
page_no = request.GET.get('p', paginator.page_range[0])
try:
page_no = int(page_no)
if not page_no in paginator.page_range:
page_no = paginator.page_range[0]
except Exception:
page_no = paginator.page_range[0]
context = {}
page = paginator.page(page_no)
objs = page.object_list
context['object_list'] = objs
context.update({
'is_paginated': paginator.num_pages > 1,
'results_per_page': paginate_by,
'page': page,
'item_number_mapping': item_number_mapping,
})
return context
示例5: list
def list(
self,
request,
queryset,
page=None,
):
"""
Renders a list of model objects to HttpResponse.
"""
template_name = '%s/%s_list.html' % (self.template_dir,
queryset.model._meta.module_name)
if self.paginate_by:
paginator = QuerySetPaginator(queryset, self.paginate_by)
if not page:
page = request.GET.get('page', 1)
try:
page = int(page)
object_list = paginator.page(page).object_list
except (InvalidPage, ValueError):
if page == 1 and self.allow_empty:
object_list = []
else:
raise Http404
current_page = paginator.page(page)
c = RequestContext(request, {
'%s_list' % self.template_object_name: object_list,
'is_paginated': paginator.num_pages > 1,
'results_per_page': self.paginate_by,
'has_next': current_page.has_next(),
'has_previous': current_page.has_previous(),
'page': page,
'next': page + 1,
'previous': page - 1,
'last_on_page': current_page.end_index(),
'first_on_page': current_page.start_index(),
'pages': paginator.num_pages,
'hits': paginator.count,
}, self.context_processors)
else:
object_list = queryset
c = RequestContext(request, {'%s_list' \
% self.template_object_name: object_list,
'is_paginated': False},
self.context_processors)
if not self.allow_empty and len(queryset) == 0:
raise Http404
# Hide unexposed fields
for obj in object_list:
self._hide_unexposed_fields(obj, self.expose_fields)
c.update(self.extra_context)
t = self.template_loader.get_template(template_name)
return HttpResponse(t.render(c), mimetype=self.mimetype)
示例6: make_pages
def make_pages(querySet, items_at_page=20, current_page=None):
pages = QuerySetPaginator(querySet, items_at_page)
page_number = validate_page_number(current_page, pages.num_pages)
posts = pages.page(page_number).object_list
context = {'items': posts}
context.update(other_pages(page_number, pages.num_pages))
return context
示例7: surveygroup_list
def surveygroup_list(request):
page_no = int(request.GET.get('page', 1))
surveygroup_list = SurveyGroup.objects.all()
p = QuerySetPaginator(surveygroup_list, 50)
page = p.page(page_no)
return render_to_response('django_surveys/surveygroup_list.html', locals(), context_instance=RequestContext(request))
示例8: survey_list
def survey_list(request, surveygroup_id):
surveygroup = get_object_or_404(SurveyGroup, pk=surveygroup_id)
survey_list = Survey.objects.filter(survey_group__id=surveygroup_id)
page_no = int(request.GET.get('page', 1))
p = QuerySetPaginator(survey_list, 50)
page = p.page(page_no)
return render_to_response('django_surveys/survey_list.html', locals(), context_instance=RequestContext(request))
示例9: index
def index(request, page=1):
"Home page with pagination. Adapted to the trunk version of paginator"
newurl = ''
#cgi.parse_qsl(request)
if (len(request.GET)>0) or (len(request.META['PATH_INFO']) >0):
if request.GET:
search_form = SearchForm(request.GET)
else:
values = {}
for k,v in cgi.parse_qs(request.META['PATH_INFO'], True).items():
if v[0] != 'None':
values[k] = v[0]
search_form = SearchForm(values)
if search_form.is_valid():
searchdict = search_form.cleaned_data
qdict = { 'first_name': 'first_name__icontains',
'last_name': 'last_name__icontains',
'age': 'age'}
q_objs = [Q(**{qdict[k]: searchdict[k]}) for k in qdict.keys() if searchdict.get(k, None)]
results = Person.objects.select_related().filter(*q_objs).order_by('first_name')
# Encode the GET data to a URL so we can append it to the next
# and previous page links.
rawurl = urllib.urlencode(searchdict)
if len(rawurl):
newurl = '&' + rawurl
else:
results = Person.objects.all()
search_form = SearchForm()
data = dict()
actual_page = int(page)
paginator = QuerySetPaginator(results,RECORDS_PER_PAGE)
try:
data['page'] = paginator.page(int(page))
except EmptyPage:
data['page'] = paginator.page(1)
actual_page = 1
data['paginator'] = paginator
data['url']='/agenda/list/page/'
#numbre of pages you want visible
if actual_page+VISIBLE_PAGES-1 <= paginator.num_pages:
start_range = actual_page
else:
start_range = max(paginator.num_pages - VISIBLE_PAGES +1,1)
end_range= min(start_range+VISIBLE_PAGES-1, paginator.num_pages)
data['range'] = range(start_range,end_range)
data['end_range'] = end_range
data['form'] = search_form
data['newurl'] = newurl
return render_to_response('agenda/index.html',data, context_instance=RequestContext(request))
示例10: search
def search(request):
import re
from pysolr import Solr
from stats.models import DailySearch
from settings import SOLR_URL
def _fail(query):
# phrase is not changed, query is normalized phrase
return render_to_response('search_results.html', {
'result': [],
'query': query,
'phrase': query,
}, context_instance=RequestContext(request))
phrase = request.GET.get('phrase')
try:
conn = Solr(SOLR_URL)
except:
return _fail(phrase)
result = []
if not phrase:
raise Http404("Malformed request.")
q = phrase
if phrase.startswith('*') or phrase.startswith('?'):
q = phrase[1:]
q = q.strip()
q = re.sub('['+'\[<>@\]'+']', '', q)
q = re.sub('`', '"', q)
q = re.sub('\s*:',':', q)
q = re.sub('(?<!author)(?<!title)(?<!text)(?<!file)(?<!tag)(?<!artist)(?<!album)(?<!year)(?<!company)(?<!created):', ' ', q)
if not q:
return _fail(phrase)
results = conn.search(q)
if not results:
return _fail(q)
ids = [i['id'] for i in results]
result = QuerySetPaginator(Topic.objects.filter(pk__in=ids), RESULTS_ON_PAGE, orphans=5)
if result.num_pages == 0:
return _fail(q)
p = DailySearch.objects.create(phrase=q.strip())
page = request.GET.get('page', 1)
try:
page = int(page)
r = result.page(page)
except (InvalidPage, ValueError):
raise Http404("No such page")
return render_to_response('search_results.html', {
'result': r,
'query': q,
'phrase': phrase,
'page': int(page),
'title': phrase,
}, context_instance=RequestContext(request))
示例11: service_listing
def service_listing(request, service_id, page_number=1):
service = get_object_or_404(DownloadService, pk=service_id)
links = service.downloadlink_set.filter(hidden=False)
paginator = QuerySetPaginator(links, 25)
page = paginator.page(page_number)
return render_response(request, 'style2/service_view.html', '/service/%s/' % service_id,
{
'service': service,
'page': page,
'paginator': paginator,
})
示例12: user_list
def user_list(request):
queryset = Timeline.objects.filter(user__is_active=True).values("user").annotate(last=Max("time")).order_by("-last")
if request.current_user:
ctype = ContentType.objects.get_for_model(User)
favorites = Favorite.objects.filter(user=request.current_user, content_type=ctype).values_list(
"object_id", flat=True
)
queryset = queryset.filter(user__id__in=favorites)
paginator = QuerySetPaginator(queryset, 20)
try:
page = paginator.page(request.GET.get("p", 1))
except (EmptyPage, InvalidPage):
page = paginator.page(paginator.num_pages)
return render_to_response(
"timeline/user_list.html",
{"user_list": [User.objects.get(id=item["user"]) for item in page.object_list], "page": page},
context_instance=RequestContext(request),
)
示例13: post_list
def post_list(request):
page_no = request.GET.get('page', 1)
if page_no == 1:
cached_page = cache.get('/')
if cached_page:
return cached_page
paginator = QuerySetPaginator(Post.objects.all(), 10)
context = {
'paginator': paginator,
'page': paginator.page(page_no),
}
response = render_to_response('blog/post_list.html', context,
RequestContext(request))
if page_no == 1:
cache.set('/', response)
return response
示例14: get_results
def get_results(self, request):
paginator = QuerySetPaginator(self.query_set, self.lookup_opts.admin.list_per_page)
# Get the number of objects, with admin filters applied.
try:
result_count = paginator.count
# Naked except! Because we don't have any other way of validating
# "params". They might be invalid if the keyword arguments are
# incorrect, or if the values are not in the correct type (which would
# result in a database error).
except:
raise IncorrectLookupParameters
# Get the total number of objects, with no admin filters applied.
# Perform a slight optimization: Check to see whether any filters were
# given. If not, use paginator.hits to calculate the number of objects,
# because we've already done paginator.hits and the value is cached.
if isinstance(self.query_set._filters, models.Q) and not self.query_set._filters.kwargs:
full_result_count = result_count
else:
full_result_count = self.manager.count()
can_show_all = result_count <= MAX_SHOW_ALL_ALLOWED
multi_page = result_count > self.lookup_opts.admin.list_per_page
# Get the list of objects to display on this page.
if (self.show_all and can_show_all) or not multi_page:
result_list = list(self.query_set)
else:
try:
result_list = paginator.page(self.page_num+1).object_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
示例15: list
def list(request, page=0):
comments = FreeComment.objects.filter(content_type=Photo, approved=True, is_public=True)
paginator = QuerySetPaginator(comments, 25, allow_empty_first_page=True)
if not page:
page = request.GET.get("page", 1)
try:
page_number = int(page)
except ValueError:
if page == "last":
page_number = paginator.num_pages
else:
raise Http404
try:
page_obj = paginator.page(page_number)
except InvalidPage:
raise Http404
return render(
request=request,
template_name="photos/comment_list.html",
payload={
"comments": comments,
"is_paginated": page_obj.has_other_pages(),
"results_per_page": paginator.per_page,
"has_next": page_obj.has_next(),
"has_previous": page_obj.has_previous(),
"page": page_obj.number,
"next": page_obj.next_page_number(),
"previous": page_obj.previous_page_number(),
"first_on_page": page_obj.start_index(),
"last_on_page": page_obj.end_index(),
"pages": paginator.num_pages,
"hits": paginator.count,
"page_range": paginator.page_range,
},
)