“Django之分页显示”的版本间的差异
来自CloudWiki
(创建页面,内容为“==技术要点== 1)数据分页显示; 2)GET方式提交参数; 3)使用模板。 ==实施步骤== ===创建模板=== 创建模板文件questionList.ht…”) |
|||
第68行: | 第68行: | ||
修改questions应用的views.py文件中的index()函数,修改题目显示方式,使用第2步中创建的模板文件。 | 修改questions应用的views.py文件中的index()函数,修改题目显示方式,使用第2步中创建的模板文件。 | ||
+ | <nowiki>@isCraw | ||
+ | def index(request): | ||
+ | #if not request.session.get('account'): | ||
+ | #return redirect('login/') | ||
+ | |||
+ | contents = Question3.objects.all() | ||
+ | #每页最多显示25条数据 | ||
+ | pages = Paginator(contents,25) | ||
+ | currentPage = request.GET.get('page') | ||
+ | try: | ||
+ | contents = pages.page(currentPage) | ||
+ | except PageNotAnInteger: | ||
+ | contents = pages.page(1) | ||
+ | except EmptyPage: | ||
+ | contents = pages.page(pages.num_pages) | ||
+ | |||
+ | #使用模板 | ||
+ | return render(request,'../templates/questionList.html', | ||
+ | {'contents':contents})</nowiki> | ||
− | + | ===运行网站=== | |
− | + | 执行命令python manage.py runserver,运行网站,使用浏览器访问http://127.0.0.1:8000/check。 | |
− |
2019年2月13日 (三) 00:28的最新版本
技术要点
1)数据分页显示;
2)GET方式提交参数;
3)使用模板。
实施步骤
创建模板
创建模板文件questionList.html。
模板文件内容如下图所示。
<html> <head> <meta charset="utf-8" /> <style type="text/css"> .center{ text-align:center; } </style> </head> <body> <div id="center"> <h1>题库列表</h1> </div> <table> <thead> <td>题干</td><td>答案</td> </thead> <tbody> {% for line in contents %} <tr><td>{{line.questionContent}}</td> <td>{{line.answer}}</td> </tr> {% endfor %} </tbody> </table> <div class="center"> <span> {% if contents.has_previous %} <a href="?page={{ contents.previous_page_number }}"> 上一页</a> {% endif %} </span> <span> 第 {{ contents.number }}页 ,共 {{ contents.paginator.num_pages }} 页 </span> <span> {% if contents.has_next %} <a href="?page={{ contents.next_page_number }}"> 下一页</a> {% endif %} </span> </div> </body> </html>
导入分页器
修改questions3应用的views.py文件,导入django提供的分页器对象。
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
修改index()函数
修改questions应用的views.py文件中的index()函数,修改题目显示方式,使用第2步中创建的模板文件。
@isCraw def index(request): #if not request.session.get('account'): #return redirect('login/') contents = Question3.objects.all() #每页最多显示25条数据 pages = Paginator(contents,25) currentPage = request.GET.get('page') try: contents = pages.page(currentPage) except PageNotAnInteger: contents = pages.page(1) except EmptyPage: contents = pages.page(pages.num_pages) #使用模板 return render(request,'../templates/questionList.html', {'contents':contents})
运行网站
执行命令python manage.py runserver,运行网站,使用浏览器访问http://127.0.0.1:8000/check。