Python--django实现分页功能

1.html测试数据

{% extends 'crm_/main_table.html' %}
{% block css %}
    
{% endblock %}
{% block table_ %}
    
{% for l in ls %} {% endfor %}
# 称号
{{ forloop.counter }} {{ l.name }} {{ l.pwd }}
{% endblock %}

2.封装的分页功能

'''
分页器
'''
from django.utils.safestring import mark_safe


class Pagination:
	def __init__(self, request, all_data, pag_data=10, max_pad=11):
		# 基本的URL
		self.base_url = request.path_info
		# 第一次返回时没有id或则是你输入的id不存在
		try:
			self.current_pad = int(request.GET.get('id'))
		except Exception as e:
			self.current_pad = 1
		ls = [{'name': 'alex{0}'.format(i), 'pwd': 'dsb{0}'.format(i)} for i in range(1, 302)]

		# 最多显示的分页个数
		self.max_pad = max_pad
		half_pad = self.max_pad // 2

		# 定义你想要显示的数据
		self.pag_data = pag_data
		# 拿到总数据数
		self.all_data = all_data
		# 用divmod内置函数,取到你要分的页数
		self.pads, pad_y = divmod(self.all_data, self.pag_data)
		if pad_y:
			self.pads += 1

			# 定义分页的开始位置和结束位置
			if self.current_pad <= half_pad:
				self.start_pad = 1
				self.end_pad = self.max_pad
			elif self.current_pad >= self.pads - half_pad:
				self.start_pad = self.pads - self.max_pad + 1
				self.end_pad = self.pads + 1
			else:
				self.start_pad = self.current_pad - half_pad
				self.end_pad = self.current_pad + half_pad
			'''
				1   1   10
				2   10  20
				3   20  30
			'''
			# 如果你的总页数小于你定义最大显示,改变它的开始和结束的位置
			if self.pads <= self.max_pad:
				self.start_pad = 1
				self.end_pad = self.pads + 1

	@property
	def StartPage(self):
		return (self.current_pad - 1) * 10

	@property
	def EndPage(self):
		return self.current_pad * 10

	def ActivePage(self):
		# 把前端代码拿过来,最后用""字符串拼接,然后再用mark_safe给标签过滤
		lst = []
		for i in range(self.start_pad, self.end_pad):
			if i == self.current_pad:
				st = '
  • {0}
  • '.format(i) else: st = '
  • {0}
  • '.format(i) lst.append(st) str_ls = mark_safe("".join(lst)) return str_ls def PrePage(self): # 上一页 if self.current_pad <= 1: st_pr = '
  • ' else: st_pr = '
  • ' \ '
  • '.format( self.current_pad - 1) st_pr = mark_safe(st_pr) return st_pr def NextPage(self): # 下一页 if self.current_pad >= self.pads: st_en = '
  • ' else: st_en = '
  • '.format( self.current_pad + 1) st_en = mark_safe(st_en) return st_en

    3.view文件中调用:

    user = [{'name': 'alex{}'.format(i), 'pwd': 'alexdsb{}'.format(i)} for i in range(1, 302)]
    def pad(request):
    	obj = Pagination(request, len(user))
    	return render(request, 'paddingex.html', {
    		'ls': user[obj.StartPage:obj.EndPage],
    		'pads': obj.ActivePage(),
    		'st_pr': obj.PrePage(),
    		'st_en': obj.NextPage()
    	})
    

     

    你可能感兴趣的:(Python宝库)