万能分页模板

views视图

def student(request):

    # all_count 数据库总个数

        all_count = models.UserInfo.objects.all().count()

        #每页显示数据数

        page_info  = PageInfo(request.GET.get('page'),all_count,10,'student.html',11)   //'student.html  配置url

        user_list = models.UserInfo.objects.all()[page_info.start():page_info.end()]#传入数据

    return render(request,'student.html',{'user_list':user_list,'page_info':page_info})


关键模板来了:

class PageInfo(object):

def __init__(self,current_page,all_count,per_page,base_url,show_page=11):

#current_page当前页

        self.current_page = current_page

try:

self.current_page =int (current_page)

except Exception as e:

self.current_page =1

        #per_page 每页显示总个数

        self.per_page = per_page

a,b=divmod(all_count,per_page)

if b:

a=a+1

        self.all_pager = a

self.show_page = show_page

self.base_url = base_url

def start(self):

return (self.current_page -1)*self.per_page

def end(self):

return self.current_page *self.per_page

def pager(self):

page_list=[]

harf =int((self.show_page-1)/2)

#如果数据总页数 < 11

        if self.all_pager

begin =1

            stop =self.all_pager+1

            # 如果数据总页数 > 11

        else:

#如果当前页<=5,永远显示1-11页

            if self.current_page <= harf:

begin =1

                stop =self.show_page+1

                # 否则当前页>5,永远显示中间页

            else:

# 如果当前页+5大于所有数据页数,永远显示最后一页

                if self.current_page + harf>self.all_pager:

begin =self.all_pager -self.show_page+1

                    stop =self.all_pager +1

                else:

begin =self.current_page - harf

stop =self.current_page+harf+1

 if self.current_page <=1:

prev ="

  • 上一页
  • "

      else:

    prev ="

  • 上一页
  • " %(self.base_url,self.current_page-1,)

    page_list.append(prev)

            for iin range(begin,stop):

    if i ==self.current_page:

    temp ="

  • %s
  • " %(self.base_url,i, i,)

    else:

    temp ="

  • %s
  • " % (self.base_url, i, i,)

    page_list.append(temp)

    if self.current_page >=self.all_pager:

    nex ="

  • 下一页
  • "

    else:

    nex ="

  • 下一页
  • " % (self.base_url,self.current_page +1,)

    page_list.append(nex)

    return ''.join(page_list)

    你可能感兴趣的:(万能分页模板)