django 自定义分页,网址存储缓存,CBV

1.

通过切片控制分页

自定义分页:

 1 from django.shortcuts import render
 2 
 3 # Create your views here.
 4 
 5 
 6 from app01.models import Book
 7 from django.core.paginator import Paginator,EmptyPage
 8 def index(request):
 9 
10     '''
11 
12     批量插入数据:
13         # for i in range(100):
14         #     Book.objects.create(title="book_%s"%i,price=i*i)
15 
16 
17         book_list=[]
18 
19         for i in range(100):
20             book=Book(title="book_%s"%i,price=i*i)
21             book_list.append(book)
22 
23         Book.objects.bulk_create(book_list)
24 
25 
26 
27     分页器的使用:
28                 paginator=Paginator(book_list,8)
29 
30                 print(paginator.count) # 100
31                 print(paginator.num_pages) # 分页数:13
32                 print(paginator.page_range) # range(1, 14)
33 
34                 page=paginator.page(5)
35                 for i in page:
36                     print(i)
37 
38                 print(page.has_next())
39                 print(page.has_previous())
40                 print(page.next_page_number())
41                 print(page.previous_page_number())
42 
43 
44 
45                     book_list = Book.objects.all()
46                     paginator = Paginator(book_list, 2)
47                     try:
48 
49                         current_page_num=request.GET.get("page",1)
50                         current_page=paginator.page(current_page_num)
51                     except EmptyPage as e:
52                         current_page_num=1
53                         current_page = paginator.page(1)
54 
55     '''
56     # 自定义分页
57 
58     print(request.GET)
59 
60 
61     from app01.page import Pagination
62     current_page_num = request.GET.get("page")
63     book_list = Book.objects.all()
64     pagination=Pagination(current_page_num,book_list.count(),request)
65     '''
66     
67     count=100
68     per_page=9
69     
70     current_page_num=1       start 0     end 8
71     current_page_num=2       start 8     end 16
72     current_page_num=3       start 16    end 24 
73     current_page_num=n       start (n-1)*per_page    end n*per_page
74     
75     '''
76     book_list=book_list[pagination.start:pagination.end]
77 
78     return render(request,"index.html",locals())
View
  1 """
  2 分页组件使用示例:
  3 
  4     obj = Pagination(request.GET.get('page',1),len(USER_LIST),request.path_info)
  5     page_user_list = USER_LIST[obj.start:obj.end]
  6     page_html = obj.page_html()
  7 
  8     return render(request,'index.html',{'users':page_user_list,'page_html':page_html})
  9 
 10 
 11 
 12 
 13 """
 14 
 15 class Pagination(object):
 16 
 17     def __init__(self,current_page_num,all_count,request,per_page_num=2,pager_count=11):
 18         """
 19         封装分页相关数据
 20         :param current_page_num: 当前访问页的数字
 21         :param all_count:    分页数据中的数据总条数
 22         :param per_page_num: 每页显示的数据条数
 23         :param pager_count:  最多显示的页码个数
 24         """
 25         try:
 26             current_page_num = int(current_page_num)
 27         except Exception as e:
 28             current_page_num = 1
 29 
 30         if current_page_num <1:
 31             current_page_num = 1
 32 
 33         self.current_page_num = current_page_num
 34 
 35         self.all_count = all_count
 36         self.per_page_num = per_page_num
 37 
 38         # 实际总页码
 39         all_pager, tmp = divmod(all_count, per_page_num)
 40         if tmp:
 41             all_pager += 1
 42         self.all_pager = all_pager
 43 
 44 
 45         self.pager_count = pager_count
 46         self.pager_count_half = int((pager_count - 1) / 2)  # 5
 47 
 48 
 49         # 保存搜索条件
 50 
 51         import copy
 52         self.params=copy.deepcopy(request.GET) # {"a":"1","b":"2"}
 53 
 54     @property
 55     def start(self):
 56         return (self.current_page_num - 1) * self.per_page_num
 57 
 58     @property
 59     def end(self):
 60         return self.current_page_num * self.per_page_num
 61 
 62     def page_html(self):
 63         # 如果总页码 < 11个:
 64         if self.all_pager <= self.pager_count:
 65             pager_start = 1
 66             pager_end = self.all_pager + 1
 67         # 总页码  > 11
 68         else:
 69             # 当前页如果<=页面上最多显示11/2个页码
 70             if self.current_page_num <= self.pager_count_half:
 71                 pager_start = 1
 72                 pager_end = self.pager_count + 1#尾页是固定的
 73             # 当前页大于5
 74             else:
 75                 # 页码翻到最后
 76                 if (self.current_page_num + self.pager_count_half) > self.all_pager:
 77 
 78                     pager_start = self.all_pager - self.pager_count + 1
 79                     pager_end = self.all_pager + 1#尾页是固定的
 80 
 81                 else:
 82                     pager_start = self.current_page_num - self.pager_count_half#+5 -5
 83                     pager_end = self.current_page_num + self.pager_count_half + 1
 84 
 85         page_html_list = []
 86 
 87         first_page = '<li><a href="?page=%s">首页</a></li>' % (1,)
 88         page_html_list.append(first_page)
 89 
 90         if self.current_page_num <= 1:
 91             prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
 92         else:
 93             prev_page = '<li><a href="?page=%s">上一页</a></li>' % (self.current_page_num - 1,)
 94 
 95         page_html_list.append(prev_page)
 96 
 97 
 98         #self.params=copy.deepcopy(request.GET) # {"a":"1","b":"2"}
 99 
100         for i in range(pager_start, pager_end):
101             #照道理来说,深拷贝是不可以添加或修改的,但是这里是可以的
102             #在返回的请求中通过添加page间而进行定位
103 
104             self.params["page"]=i
105 
106             if i == self.current_page_num:
107                 temp = '<li class="active"><a href="?%s">%s</a></li>' %(self.params.urlencode(),i)
108             else:
109                 temp = '<li><a href="?%s">%s</a></li>' % (self.params.urlencode(),i,)
110             page_html_list.append(temp)
111 
112 
113 
114 
115 
116 
117 
118 
119         if self.current_page_num >= self.all_pager:
120             next_page = '<li class="disabled"><a href="#">下一页</a></li>'
121         else:
122             next_page = '<li><a href="?page=%s">下一页</a></li>' % (self.current_page_num + 1,)
123         page_html_list.append(next_page)
124         last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
125         page_html_list.append(last_page)
126 
127         return ''.join(page_html_list)
page.py
 1 <!DOCTYPE html>
 2 <html lang="zh-CN">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <meta name="viewport" content="width=device-width, initial-scale=1">
 7     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
 8 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 9 </head>
10 <body>
11 
12 <ul>
13     {% for book in book_list %}
14     <li>{{ book.title }} ---- {{ book.price }}</li>
15     {% endfor %}
16 </ul>
17 
18 <nav aria-label="Page navigation">
19   <ul class="pagination">
20    {{ pagination.page_html|safe }}......
21   </ul>
22 </nav>
23 
24 
25 </body>
26 </html>
login.html

2.

 1 FBV-----function based view    
 2 CBV-----class  based view
 3         
 4     path('index/', views.index),
 5     path('login/', views.LoginView.as_view()),
 6     path('login/', View.as_view.view)
 7     # 用户访问get请求/login/-----------view(request)
 8     
 9     def view(request):
10         self = cls(**initkwargs)
11         return self.dispatch(request, *args, **kwargs)
12         
13         def dispatch(request, *args, **kwargs):
14                 if request.method.lower() in self.http_method_names:
15                     handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
16                 else:
17                     handler = self.http_method_not_allowed
18                 return handler(request, *args, **kwargs)
19     
CBV源码
1 from django.contrib import admin
2 from django.urls import path
3 
4 from app01 import views
5 
6 urlpatterns = [
7     path('admin/', admin.site.urls),
8     path('login/', views.LoginView.as_view()),
9 ]
urls

过程, as_view-- def view -- def dispatch --进行校验,返回

原文地址:https://www.cnblogs.com/zhangqing979797/p/9925199.html