1、创建数据库信息
class UserList(models.Model):
username = models.CharField(max_length=32)
age = models.IntegerField()
2、创建URL
from app01 import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^user_list/‘, views.user_list),
]
3、定义一个Pager类,处理页数换算
class Pager(object):
def __init__(self, current_page):
self.current_page = int(current_page)
@property
def start(self):
return (self.current_page - 1) * 10
@property
def end(self):
return self.current_page * 10
def page_str(self, all_item, base_url):
all_page, div = divmod(all_item, 10)
if div > 0:
all_page += 1
pager_list = []
if all_page <= 11:
start = 1
end = all_page
else:
if self.current_page <= 6:
start = 1
end = 12
else:
start = self.current_page - 5
end = self.current_page + 6
if self.current_page + 6 > all_page:
start = all_page - 11
end = all_page + 1
for i in range(start, end):
if i == self.current_page:
temp = ‘<a style="colo:red;font-size:26px;" href="%s%d">%d</a>‘ % (base_url, i, i,)
else:
temp = ‘<a href="%s%d">%d</a>‘ % (base_url, i, i)
pager_list.append(temp)
# pre_next
if self.current_page > 1:
pre_page = ‘<a href="%s%d">pre_next</a>‘ % (base_url, self.current_page - 1)
else:
pre_page = ‘<a href="javascript:void(0);">pre_next</a>‘
# next
if self.current_page >= all_page:
next_page = ‘<a href="javascript:void(0);">next</a>‘
else:
next_page = ‘<a href="%s%d">next</a>‘ % (base_url, self.current_page + 1)
pager_list.insert(0, pre_page)
pager_list.append(next_page)
return mark_safe("".join(pager_list))
4、创建视图 ,并导入上面创建的Pager类
def user_list(request):
current_page=request.GET.get(‘page‘,1)
page_obj = page.Pager(current_page)
result = models.UserList.objects.all()[page_obj.start:page_obj.end]
all_item = models.UserList.objects.all().count()
pager_str = page_obj.page_str(all_item, "/user_list/?page=")
return render(request, ‘user_list.html‘, {‘result‘: result, ‘pager_str‘: pager_str})
5、创建前端user_list.html调用后台信息。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
a{
padding: 5px;
}
</style>
</head>
<body>
<table>
{% for line in result %}
<tr>
<td>{{ line.username }}</td>
<td>{{ line.age }}</td>
</tr>
{% endfor %}
</table>
<div>
{{ pager_str|safe }}
</div>
</body>
</html>
原文地址:http://dzlly1.blog.51cto.com/932657/1762011