Moh*_*itC 6 django ajax jquery django-pagination
我有一个视图将分页对象(在查询集上)发送到模板,我在模板中进一步将其呈现为表格。我想要做的是单击模板上分页栏上的页码,它应该进行 ajax 调用以获取该页码的分页输出并使用它动态更新表格的内容。
看法:
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)
Run Code Online (Sandbox Code Playgroud)
模板将其加载为:
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
现在对于分页栏,我正在使用Bootpag 的库,我可以将内容呈现为:
$('.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
}
Run Code Online (Sandbox Code Playgroud)
抱歉,我没有展示我在 ajax 部分尝试过的大部分内容,因为我对如何在不重新加载页面的情况下使模板重新呈现返回的新帐户完全空白。
我能想到的唯一肮脏的解决方案是在视图中生成我的整个 html,然后使用返回的新 html ajax 更新表 div 的 html?
使用不重新加载页面编写的模板渲染逻辑重新加载表 div 的简单方法是什么?这可以通过使表部分成为一个单独的模板并包含/扩展模板来实现吗?
请注意,我不能使用获取模板上的所有数据然后使用某些jquery/js libaray 的分页逻辑的方法,因为完整的数据相对非常大。
我解决了以下问题:
将表格部分作为模板 table.html 分隔为:
应用程序/table.html:
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
在主模板 main.html 中将其称为包含模板:
应用程序/main.html:
<div class="table-responsive">
{% include 'app/table.html' %}
</div>
Run Code Online (Sandbox Code Playgroud)
现在在我看来,我添加了一行,仅table.html当请求是 ajax 请求时才会呈现。
if request.is_ajax():
return render(request, 'app/table.html', context)
#else
return render(request, 'app/main.html', context)
Run Code Online (Sandbox Code Playgroud)
重新加载分页表为:
$('.pagination_top').bootpag({
/*bootpag logic here */
}).on("page", function(event, num){
$(".table-responsive").html('').load(
"{% url 'app:accounts' %}?page=" + num
);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7794 次 |
| 最近记录: |