自定义html_helper.py —> Page_helper类
#coding:utf-8 from django.utils.safestring import mark_safe class Page_Helper(object): def __init__(self,page,html_string,page_space,host): self.Page = page self.Html_string = html_string self.Page_space = page_space self.Host = host @property def begin(self): begin = int((self.Page - 1) * self.Page_space) return begin @property def end(self): end = int(self.Page * self.Page_space) return end def page_html(self,all_count): result, residue = divmod(all_count, self.Page_space) first_page = '<a href = "/Page/%d" > 首页 </a>' %(1,) self.Html_string.append(first_page) if self.Page == 1: last_page = '<a href = "/Page/%d" > 上一页 </a>' %(1,) else: last_page = '<a href = "/Page/%d" > 上一页 </a>' %(self.Page-1,) self.Html_string.append(last_page) if residue == 0: result = result else: result = result + 1 if result < 11: start_dir = 0 end_dir = result else: if self.Page < 6: start_dir = 0 end_dir = self.Page + 4 else: if self.Page + 4 < result: start_dir = self.Page - 5 end_dir = self.Page + 4 else: start_dir = self.Page -5 end_dir = result for i in range(start_dir,end_dir): if self.Page == i + 1: label_html = "<a style='color:red;' href = '/Page/%d' > %d </a>" % (i + 1, i + 1) else: label_html = '<a href = "/Page/%d" > %d </a>' %(i+1,i+1) self.Html_string.append(label_html) next_page = '<a href = "/Page/%d" > 下一页 </a>' %(self.Page+1,) self.Html_string.append(next_page) end_page = '<a href = "/Page/%d" > 尾页 </a>' %(result,) self.Html_string.append(end_page) pass_string = mark_safe(''.join(self.Html_string)) return pass_string
在views定义函数
def Page(request,page): html_string = [] page = int(page) page_space = 5 helper = Page_Helper(page,html_string,page_space,Host) all_discover = Host.objects.all()[helper.begin:helper.end] all_count = Host.objects.all().count() pass_string =helper.page_html(all_count) return render_to_response('page.html',{'data':all_discover,'pass_string':pass_string})
设置路由进行访问
url(r'Page/(\d*)',views.Page),
原创文章,作者:心肝坏了,如若转载,请注明出处:http://www.178linux.com/37956