首页 > 代码库 > 简单分页步骤

简单分页步骤

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 =http://www.mamicode.com//index/{}>首页<a>.format(1)
    links.append(first_link)
    prev_link =<a href =http://www.mamicode.com//index/{}>上一页<a>.format(page-1)
    links.append(prev_link )
    for i in range(sum):
        if page == i+1:
            link = <a style=clour:red; href =http://www.mamicode.com//index/{}>{}<a>.format(i+1,i+1)
        else:
            link = <a href =http://www.mamicode.com//index/{}>{}<a>.format(i+1,i+1)
        links.append(link)
    next_link = <a href =http://www.mamicode.com//index/{}>下一页<a>.format(page+1)
    links.append(next_link )
    end_link = <a href =http://www.mamicode.com//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

 

简单分页步骤