开发者

Pagination problem

I'm using this code for my pagination, and I'd like the user's choice to be pe开发者_如何学编程rsistent throughout the site (this has been solved so far)...the only problem now is that the session variable now is permanent until the session is cleared by closing the browser. Also, how can I get the adjacent pages displayed...like in the digg-style Django paginator. I haven't been able to make sense of how to implement this into my code.

The code is as follows:

from django.core.paginator import Paginator, InvalidPage, EmptyPage

def paginate(request, object_list, paginate_by=10):
   try:
      if "per_page" in request.session:
        per_page = request.session["per_page"]
      else:
        request.session["per_page"] = int(request.REQUEST['p'])
        per_page = request.session["per_page"]
        request.session.set_expiry(0)
   except:
      per_page = 10

   paginator = Paginator(object_list, per_page)

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

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

   return items

Then in my template I have this to render the pagination links:

<div class="pagination" align="center"> 
 <span class="step-links"> 
  {% if items.has_previous %} 
    <a href="?page={{ items.previous_page_number }}">previous</a> 
  {% endif %} 
  <span class="current"> 
    Page {{ items.number }} of {{ items.paginator.num_pages }} 
  </span> 
  {% if items.has_next %} 
    <a href="?page={{ items.next_page_number }}">next</a> 
  {% endif %} 
 </span> 
</div>


You can achieve this by enabling sessions.

I recommend reading through the chapter Sessions, Users, and Registration on the djangobook website.


Edit: Now that you've enabled sessions, I think the problem is the hyperlinks in the template. Use an ampersand to separate multiple parameters in a url, for example

 <a href="?p={{ request.session.per_page }}&page={{ items.next_page_number }}">next</a> 

Edit 2: I'm not sure if I understand what the problem is with the session expiry. The line that sets the session to expire when the browser closes is request.session.set_expiry(0). See the django docs on Using Sessions in views if you want to change that.

To make a Digg style paginator, you need to write a function that takes the current page number and the total number of pages, and returns a list of page numbers. Then, in the template, loop through the page numbers and construct links to the pages.

A list of lists of page numbers would allow you to split the page numbers into groups, eg

[[1,2], [20,21,22,23,24], [30,31]]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜