def get_context_data(self, **kwargs):
context = super(TwitsListView, self).get_context_data(**kwargs)
twit_lists = self.get_queryset()
paginator = Paginator(twit_lists, self.paginate_by)
try:
page = self.kwargs['page']
except:
page = 1
try:
twits = paginator.page(page)
except PageNotAnInteger:
twits = paginator.page(1)
except EmptyPage:
twits = paginator.page(paginator.num_pages)
context['twits'] = twits
context['twit_slug'] = self.kwargs['twit_slug']
return context
python类Paginator()的实例源码
def index(request):
posts_list = Post.objects.all() # .order_by("-timestamp")
paginator = Paginator(posts_list, 5)
page_var = 'page1'
page = request.GET.get(page_var)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
context = {
'page_title': 'List of Posts',
'posts': posts,
'page_var': page_var
}
return render(request, 'posts/index.html', context)
def list_vulns(request, vuln_list):
myList = []
for vt in vuln_list:
positives = VulnerabilityResult.objects.all().filter(name=vt)
apps = set(App.objects.filter(vulnerabilityresult__name=vt))
myList.append({"name":vt, "count":positives.count, "appcount":len(apps)})
myList.sort(key= lambda vt:vt['appcount'], reverse=True)
paginator = Paginator(myList,20)
page = request.GET.get('page')
try:
vulns = paginator.page(page)
except PageNotAnInteger:
vulns = paginator.page(1)
except EmptyPage:
vulns = paginator.page(paginator.num_pages)
context = {'vulns':vulns}
return render_to_response('frontpage/static_vulns.html', RequestContext(request, context))
views.py 文件源码
项目:Django-Web-Development-with-Python
作者: PacktPublishing
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def movie_list(request):
paginator = Paginator(TOP_MOVIE_LIST, 25)
page_number = request.GET.get("page")
try:
page = paginator.page(page_number)
except PageNotAnInteger:
# If page is not an integer, show first page.
page = paginator.page(1)
except EmptyPage:
# If page is out of range, show last existing page.
page = paginator.page(paginator.num_pages)
context = {
"object_list": page,
}
return render(request, "movies/movie_list.html", context)
def list_guazi(request):
after_range_num = 5
before_range_num = 4
page_size = 20
Guazi_list = GuaziCar.objects.all().order_by('-id')
paginator = Paginator(Guazi_list, page_size)
try:
page = int(request.GET.get('page','1'))
if page < 1:
page=1
except ValueError:
page=1
try:
carlist = paginator.page(page)
except (EmptyPage,InvalidPage,PageNotAnInteger):
carlist = paginator.page(1)
if page >= after_range_num:
page_range = list(paginator.page_range)[page-after_range_num:page+before_range_num]
else:
page_range = list(paginator.page_range)[0:int(page)+before_range_num]
return render(request, 'guazi.html', {'guazi_list': carlist, 'page_range': page_range})
def get_page(self, data):
try:
page_no = int(self.request.GET.get(self.page_attribute_name, 1))
except (TypeError, ValueError):
raise NotFound('Invalid page number.')
if page_no < 1:
raise NotFound('Page number should be 1 or greater.')
# Explicitly evaluate data before sending it to Paginator, otherwise
# (at least in the case of RelatedSearchQuerySet) the total count
# goes completely wrong
# see: https://github.com/django-haystack/django-haystack/issues/362
data[:self.results_per_page]
paginator = Paginator(data, self.results_per_page)
try:
page = paginator.page(page_no)
except InvalidPage:
raise NotFound('No such page!')
return page
def view_station(request, station_id):
station = get_object_or_404(Station, abbreviation=station_id)
incidents = Incident.objects.filter(
station__id=station.id,
).order_by('-incident_dt')
incidents_count = len(incidents)
paginator = Paginator(incidents, 25)
page = request.GET.get('page')
try:
incidents = paginator.page(page)
except PageNotAnInteger:
incidents = paginator.page(1)
except EmptyPage:
incidents = paginator.page(paginator.num_pages)
return render(request, 'station.html', {'incidents_count': incidents_count,
'station': station,
'incidents': incidents})
def incidents_for_tag(request, slug):
tag = get_object_or_404(Tag, slug=slug)
incidents = Incident.objects.filter(
tags__id=tag.id,
).order_by('-incident_dt')
incidents_count = len(incidents)
paginator = Paginator(incidents, 25)
page = request.GET.get('page')
try:
incidents = paginator.page(page)
except PageNotAnInteger:
incidents = paginator.page(1)
except EmptyPage:
incidents = paginator.page(paginator.num_pages)
return render(request, 'tag.html', {'tag': tag, 'incidents': incidents,
'incidents_count': incidents_count})
# pylint: disable=too-many-ancestors
def results(request, template_name="search/results.html"):
""" template for displaying settings.PRODUCTS_PER_PAGE paginated product results """
# get current search phrase
q = request.GET.get('q', '')
# get current page number. Set to 1 is missing or invalid
try:
page = int(request.GET.get('page', 1))
except ValueError:
page = 1
matching = search.products(q).get('products', [])
# generate the pagintor object
paginator = Paginator(matching,
settings.PRODUCTS_PER_PAGE)
try:
results = paginator.page(page).object_list
except (InvalidPage, EmptyPage):
results = paginator.page(1).object_list
search.store(request, q)
page_title = 'Search Results for: ' + q
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def paginate(request, qs):
try:
limit = int(request.GET.get('limit', 10))
except ValueError:
limit = 10
if limit > 100:
limit = 10
try:
page = int(request.GET.get('page', 1))
except ValueError:
raise Http404
paginator = Paginator(qs, limit)
try:
page = paginator.page(page)
except EmptyPage:
page = paginator.page(paginator.num_pages)
return page, paginator
def get_context(self, request):
context = super(HutIndexPage, self).get_context(request)
page = request.GET.get('page')
tag = request.GET.get('tag')
pages = HutPage.objects.child_of(self).live()
if tag:
pages = pages.filter(facilities__slug__iexact=tag)
context['tag'] = Tag.objects.get(slug__iexact=tag)
paginator = Paginator(pages, 10) # Show 10 huts per page
try:
pages = paginator.page(page)
except PageNotAnInteger:
pages = paginator.page(1)
except EmptyPage:
pages = paginator.page(paginator.num_pages)
context['children'] = pages
return context
def index(request):
template = get_template('index.html')
attractions_data = Attractions.objects.all()
paginator = Paginator(attractions_data, 5) # Show 10 content per page
page = request.GET.get('page')
try:
content = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
content = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
content = paginator.page(paginator.num_pages)
index = content.number
max_index = len(paginator.page_range)
start_index = max_index - 7 if index >= max_index - 5 else index - 1 if index != 1 else 1
end_index = max_index + 1 if index >= max_index - 6 else index + 7 if index != 1 else index + 8
page_range = range(start_index, end_index)
html = template.render(locals())
return HttpResponse(html)
def index(request) :
pageLimit = 10
#Entry.objects.order_by(Coalesce('summary', 'headline').desc()) #asc()
qwests = Question.objects.all().order_by('-id')
from django.core.paginator import Paginator
page = request.GET.get('page') or 1
try :
page = int(page)
except ValueError :
page = 1
paginator = Paginator(qwests, pageLimit)
paginator.baseurl = '/?page='
try :
page = paginator.page(page)
except EmptyPage :
page = paginator.page(paginator.num_pages)
return render(request, 'questionList.html', {
'title' : 'qwests and answers',
'list' : page.object_list,
'paginator' : paginator,
'page' : page,
})
def popular(request) :
pageLimit = 10
#Entry.objects.order_by(Coalesce('summary', 'headline').desc()) #asc()
qwests = Question.objects.all().order_by('-likes')
from django.core.paginator import Paginator
page = request.GET.get('page') or 1
try :
page = int(page)
except ValueError :
page = 1
paginator = Paginator(qwests, pageLimit)
paginator.baseurl = '/?page='
try :
page = paginator.page(page)
except EmptyPage :
page = paginator.page(paginator.num_pages)
return render(request, 'questionList.html', {
'title' : 'popular quests',
'list' : page.object_list,
'paginator' : paginator,
'page' : page,
})
def post_list(request, tag_slug=None):
object_list = Post.published.all()
tag = None
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
object_list = object_list.filter(tags__in=[tag])
paginator = Paginator(object_list, 3) # 3 posts in each page
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer deliver the first page
posts = paginator.page(1)
except EmptyPage:
# If page is out of range deliver last page of results
posts = paginator.page(paginator.num_pages)
return render(request,'blog/post/list.html',{'page': page, 'posts': posts, 'tag':tag})
def image_list(request):
images = Image.objects.all()
paginator = Paginator(images, 8)
page = request.GET.get('page')
try:
images = paginator.page(page)
images_by_popularity = Image.objects.order_by('-total_likes')
except PageNotAnInteger:
if request.is_ajax():
# If page is not an integer deliver the first page
images = paginator.page(1)
except EmptyPage:
if request.is_ajax():
# If the request AJAX and the page is out of range
# return an empty page
return HttpResponse('')
# If page is out of range deliver last page of results
images = paginator.page(paginator.num_pages)
if request.is_ajax():
return render(request, 'images/image/list_ajax.html',{'section': 'images', 'images': images})
return render(request, 'images/image/list.html', {'section': 'images', 'images': images})
def album_detail(request, pk):
album = get_object_or_404(Album, pk=pk)
photo_list = album.photo_set.all()
paginator = Paginator(photo_list, 4)
page = request.GET.get('page')
try:
photos = paginator.page(page)
except PageNotAnInteger:
photos = paginator.page(1)
except EmptyPage:
photos = paginator.page(paginator.num_pages)
context = {
'album': album,
'photos': photos,
}
# template_file = 'photo/album_detail.html'
template_file = 'photo/ajax_album_detail.html'
return render(request, template_file, context)
def html_page(request):
service_name = request.GET.get('service_name')
log_path = dao_config.log_dir_master
service_name_path = log_path + service_name
all_file = []
for i in os.listdir(service_name_path):
file_path = service_name_path +'/' + i
if os.path.isfile(file_path):
all_file.append([i,file_path])
print(all_file)
all_file = sorted(all_file, key=lambda file_name: file_name[1])
paginator = Paginator(all_file, 10) # Show 25 contacts per page
page = request.GET.get('page')
try:
contacts = paginator.page(page)
except PageNotAnInteger:
contacts = paginator.page(1)
except EmptyPage:
contacts = paginator.page(paginator.num_pages)
return render(request, 'cat_down_log.html', {"contacts": contacts,'service_name':[service_name]})
def host_list(request):
"""
List all Hosts
"""
user = request.user
host_list = HostList.objects.all().order_by('-status')
# host_list = HostList.objects.all()
paginator = Paginator(host_list,10)
try:
page = int(request.GET.get('page','1'))
except ValueError:
page = 1
try:
host_list = paginator.page(page)
except :
all_host = paginator.page(paginator.num_pages)
return render(request, 'host_list.html', {'host_list': host_list, 'page': page, 'paginator':paginator})
# return render(request, 'host_list.html',{'host_list': host_list})
def system_install_record(request):
"""
List all operating system installation records
"""
user = request.user
record = InstallRecord.objects.all().order_by('-install_date')
paginator = Paginator(record,10)
try:
page = int(request.GET.get('page','1'))
except ValueError:
page = 1
try:
record = paginator.page(page)
except :
record = paginator.page(paginator.num_pages)
return render(request, 'install_record_list.html', {'record': record, 'page': page, 'paginator':paginator})