本文整理汇总了Python中django.core.paginator.QuerySetPaginator.page方法的典型用法代码示例。如果您正苦于以下问题:Python QuerySetPaginator.page方法的具体用法?Python QuerySetPaginator.page怎么用?Python QuerySetPaginator.page使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.paginator.QuerySetPaginator
的用法示例。
在下文中一共展示了QuerySetPaginator.page方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: home
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
def home(request, model="s", objectId="0", page_num=1, template='home.html'):
paginate_by = settings.PAGINATE_BY
#what we get as parameter is always a string
page_num = int(page_num)
if model == 'u': #for user we need to filter for the user
info_list = Paginator(sol.objects.filter(author__username=objectId), paginate_by)
elif model== 's': #for sol; home page
if objectId == '0':
info_list = Paginator(sol.objects.all(), paginate_by)
else:
info_list = Paginator(sol.objects.filter(id=objectId), paginate_by)
elif model =='g': #for group
if objectId == '0':
info_list = Paginator(group.objects.all(), paginate_by)
else:
info_list = Paginator(sol.objects.filter(group=group.objects.get(id=objectId)), paginate_by)
#if the user altered the URL for a particular page that doesn't exist
try:
page_info = info_list.page(page_num)
except InvalidPage:
page_num = 1
page_info = info_list.page(page_num)
has_previous = page_info.has_previous()
has_next = page_info.has_next()
info_dict = {
'query_list' : page_info.object_list,
'has_previous' : page_info.has_previous(),
'previous_page' : page_info.previous_page_number(),
'has_next' : page_info.has_next(),
'next_page' : page_info.next_page_number(),
'site_name' : settings.SITE_NAME,
'user' : request.user,
}
if model == 's':
form = solForm()
#this is how you append to a dict
info_dict['solForm'] = form
if model == 'u':
#this is how you append to a dict
info_dict['u_id'] = objectId
info_dict['nickname'] = userprofile.objects.get(user__username=objectId).nickname
if model == 'g':
info_dict['grpForm'] = grpForm()
if objectId == '0':
info_dict['solForm'] = solForm()
else:
info_dict['solForm'] = solForm(initial={'group': group.objects.get(id=objectId)})
info_dict['grpId'] = objectId
info_dict['grpName'] = group.objects.get(id=objectId).desc
return render_to_response(template, info_dict)
示例2: list
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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)
示例3: index
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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))
示例4: paginate_queryset_for_request
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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: series_and_issue
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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)
示例6: detail
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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)
)
示例7: list
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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)
示例8: user_list
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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),
)
示例9: make_pages
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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
示例10: surveygroup_list
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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))
示例11: survey_list
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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))
示例12: search
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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))
示例13: service_listing
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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,
})
示例14: post_list
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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
示例15: get_results
# 需要导入模块: from django.core.paginator import QuerySetPaginator [as 别名]
# 或者: from django.core.paginator.QuerySetPaginator import page [as 别名]
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