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 = '%d' % (base_url, i, i,)
else:
temp = '%d' % (base_url, i, i)
pager_list.append(temp)
# pre_next
if self.current_page > 1:
pre_page = 'pre_next' % (base_url, self.current_page - 1)
else:
pre_page = 'pre_next'
# next
if self.current_page >= all_page:
next_page = 'next'
else:
next_page = 'next' % (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调用后台信息。
a{
padding: 5px;
}
{% for line in result %}
` line`.`username `` line`.`age `{% endfor %}
{{ pager_str|safe }}