简单分页步骤

Posted on 2016-11-30 19:22  哇好大哦  阅读(167)  评论(0编辑  收藏  举报

urls:

url(r'^index/(\d*)',views.index)

views:

from django.shoutcuts import render
from app impost models
from app import common
from django.utils.safestring import make_safe

def index(request,page):
    page = common.try_int(page,1)

    per_item = 5   #每页显示5条
    start = (page-1)*per_item
    end =page-*per_item 
    
    count = models.Host.objects.all().count()
    result = models.Host.objects.all()[start:end]
    
    sum = -(-count//per_item)   #总共多少页
    links=[]
    first_link = '<a href ='/index/{}'>首页<a>'.format(1)
    links.append(first_link)
    prev_link ='<a href ='/index/{}'>上一页<a>'.format(page-1)
    links.append(prev_link )
    for i in range(sum):
        if page == i+1:
            link = '<a style='clour:red;' href ='/index/{}'>{}<a>'.format(i+1,i+1)
        else:
            link = '<a href ='/index/{}'>{}<a>'.format(i+1,i+1)
        links.append(link)
    next_link = '<a href ='/index/{}'>下一页<a>'.format(page+1)
    links.append(next_link )
    end_link = '<a href ='/index/{}'>尾页<a>'.format(sum)
    links.append(end_link)

    page = make_safe(''.join(links))    #把字符串变成可以显示的代码
    ret ={'count':count,'data':result,'page':page}
    
    return render(request,'index.html',ret)                

common:

def try_int(arg,default):
    try:
        arg = int(arg)
    expect Expection:
        arg = default
    return arg
View Code

 

Copyright © 2024 哇好大哦
Powered by .NET 8.0 on Kubernetes