如何从python xrange中获取某些条目 - django paginator

时间:2016-02-05 00:40:53

标签: python django

我正在使用Django paginator并试图让它在底部显示多个页面。目前我正在设置它以便它只会显示当前数字周围的几个数字(例如,接下来2 3 4 5 6 prev),我知道我将如何做到这一点然而我正在努力django的分页如何存储page_range。它将它存储为x_range,因此我不知道如何从中获取某些值。

middle = job_listings.paginator.page_range[before:after]

这就是我想要做的但是它返回以下错误。谁能告诉我如何从xrange中获取一系列项目?

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/listings/browse?page=4

Django Version: 1.9.1
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'main',
 'listings',
 'profiles',
 'allauth',
 'allauth.account',
 'allauth.socialaccount')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')



Traceback:

File "C:\Python27\Lib\site-packages\django\core\handlers\base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "C:\Python27\Lib\site-packages\django\core\handlers\base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "D:\Other folders\Desktop\Student Job Search\code\opus_jobs_project\listings\views.py" in browse
  54.     middle = job_listings.paginator.page_range[before:after]

Exception Type: TypeError at /listings/browse
Exception Value: sequence index must be integer, not 'slice'

潜在相关的分页代码 -

job_listings_list = JobListing.objects.filter(filters).distinct().order_by('-listing_date')
print(job_listings_list)

paginator = Paginator(job_listings_list, 1) # Show 25 contacts per page

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

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

current_page_start = job_listings.start_index()
current_page_end = job_listings.end_index()

before_current_pages=1
after_current_pages=1
before = max(job_listings.number - before_current_pages, 0)
after = job_listings.number + after_current_pages
middle = job_listings.paginator.page_range[before:after]
print("before", before, "after", after)

(如果您需要更多代码,请告诉我们)

1 个答案:

答案 0 :(得分:1)

您可以通过调用列表来使用xrange对象作为列表。

>>> x = xrange(5)
>>> x
xrange(5)
>>> list(x)
[0, 1, 2, 3, 4]