views中使用分页库Paginator.page
先导入Page, Paginator
from django.core.paginator import Page, Paginator
def paper(request,topic_id):
#获取对应主题对象
topic_t = Topic.objects.get(id=topic_id)
#展示对象
paper_qs = topic_t.paper.paper_quest.all()
#分页器,每页显示1条记录
paginator = Paginator(paper_qs,1)
#获取用户页面的页数
page = request.GET.get('page')
try:
# GET请求方式,get()获取指定Key值所对应的value值
# 获取index的值,如果没有,则设置使用默认值1
contacts = paginator.page(page)
except PageNotAnInteger:
# 如果输入的页码数不是整数,那么显示第一页数据
contacts = paginator.page(1)
except EmptyPage:
contacts = paginator.page(paginator.num_pages)
context = {
#分页对象
'contacts':contacts
return render(request,'quest/paper.html',context)
模板页面:paper.html
"""翻页栏"""
<div class="pagination" >
<span class="step-links">
{% if contacts.has_previous %}
<a href=" ?page={{ contacts.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
</span >
{% if contacts.has_next %}
<a href=" ?page={{ contacts.next_page_number }}">next</a>
{% endif %}
"""读取每页的内容,并通过属性展示出来,添加按钮变成点击获取和传递值,并打开下一页."""
{% for contact in contacts %}
{# Each "contact" is a Contact model object. #}
{% if contacts.has_next %}
<var> {{contact.id}} </var>{{contact}}
<p><button type="button" class="btn btn-default btn-lg btn-block" id="b1"
value="{{contact.answer_A_score}}"
"""使用ajax传递按钮数据,同时传递其他变量到views的compute函数
<script>
var topic_id = {{ topic_t.id }};
var quest_id = {{ contacts.number }};
$("#b1").click(function () {
$.ajax({
url: " {% url 'quest:compute' %} ",
type: "post",
data: {
"id": $("#b1").val(),
"topic_id":topic_id,
"quest_id":quest_id,
"csrfmiddlewaretoken": $("[name='csrfmiddlewaretoken']").val()
},
success: function (res){
$('#m1').val(res)
},
error: function (err) {
console.log(err);
}
})
})
</script>
tips :
需要在js中先将定义变量,才能传递var
分页实例对象contacts可以获取值,但是在循环中contact实例在页面可以展示,但是不能获取值,不明白为什么?。。。。。。因为没有var