我有一个视图,它将查询集中的分页对象(发送到查询集)发送到模板,我将模板作为表格进一步呈现。我想要做的是点击模板上的分页栏上的页码,它应该进行ajax调用,以获得该页码的分页输出,并动态更新表的内容。如何在AJAX调用中重新呈现Django模板代码
查看:
def accounts(request):
#Including only necessary part
accounts_list = Accounts.objects.all()
paginator = Paginator(accounts_list, 25)
page = request.GET.get('page')
try:
accounts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
accounts = paginator.page(1)
except EmptyPage:
# If page is out of range, deliver last page of results.
accounts = paginator.page(paginator.num_pages)
context['accounts'] = accounts
return render(request, template, context)
模板加载此为:
{% if accounts %}
<table id="acc">
<tr>
<th>Field 1</th>
...
<th>Field N</th>
</tr>
{% for item in accounts %}
<tr>
<td>{{ item.field1 }}</td>
...<!-- Some complex logic with template tags too in here -->
<td>{{ item.fieldN }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
现在对于分页栏,我使用Bootpag's library,我可以渲染的东西为:
$('.pagination_top').bootpag({
/*bootpag logic here */
}).on("page", function(event, num){
//$.ajax loading here where I can update the table div with new output
//or make the table div "template code" reload without reloading page
}
对不起,我有没有显示我在ajax部分尝试过的东西,因为我完全空白了如何让模板重新呈现无需重新加载页面而返回的新帐户。
我能想到的唯一肮脏的解决方案是在视图中生成我的整个html,然后用新的html ajax返回更新表格div的html?
什么是简单的方法来说,重新加载表格div使用模板渲染逻辑写入没有重新加载页面?这可以通过将表格部分作为单独的模板并包含/扩展模板来实现?
请注意,我不能使用一种方法获取模板上的所有数据,然后使用一些jquery/js libaray的分页逻辑,因为完整的数据是相当大的。
你的js脚本仍在重新加载页面,页面url是否随着每次点击而改变? – sgauri