如何在AJAX调用上重新呈现django模板代码

我有一个视图,它将分页对象(在查询集上)发送到模板,我在模板中进一步呈现为一个表。 我要做的是点击模板上的分页栏上的页码,它应该进行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) 

模板加载为:

 {% if accounts %}  ...  {% for item in accounts %}  ... {% endfor %} 
Field 1Field N
{{ item.field1 }} {{ item.fieldN }}
{% endif %}

现在为分页栏,我使用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 } 

抱歉,我没有在ajax部分上展示过很多内容,因为我完全空白如何在不重新加载页面的情况下重新渲染新模板。

我能想到的唯一脏解决方案是在视图中生成我的整个html然后用新的html ajax返回更新表div的html?

使用在不重新加载页面的情况下编写的模板渲染逻辑来重新加载表格div的简单方法是什么? 这可以通过使表格部分成为一个单独的模板并包含/扩展模板来实现吗?

请注意,我不能使用一种方法来获取模板上的所有数据,然后使用某些jquery / js libaray的分页逻辑,因为完整的数据相对非常大。

我解决了以下问题:

将表格部分分隔为模板table.html:

应用程序/ table.html:

 {% if accounts %}  ...  {% for item in accounts %}  ... {% endfor %} 
Field 1Field N
{{ item.field1 }} {{ item.fieldN }}
{% endif %}

在主模板main.html中将其称为包含模板:

应用程序/ main.html中:

 
{% include 'app/table.html' %}

现在在我看来,如果request是ajax请求,我添加了一行只呈现table.html

 if request.is_ajax(): return render(request, 'app/table.html', context) #else return render(request, 'app/main.html', context) 

重新加载分页表:

 $('.pagination_top').bootpag({ /*bootpag logic here */ }).on("page", function(event, num){ $(".table-responsive").html('').load( "{% url 'app:accounts' %}?page=" + num ); }); 

如果你想依赖django模板,你应该重新加载页面并通过请求中的分页信息发送。 这是通常所做的(例如在django-admin中)。 它需要重新加载页面,但这就是为django模板制作的。

否则,我会将整个渲染委托给客户端,并在django中仅提供JSON视图。 这样,django将提供一个模板,其中包含一些标记以及您最喜欢的js库,它负责进行AJAX调用并直接在其上呈现数据。

更新:

如果你真的需要这样做,你提到的方法是可能的。 没有什么能阻止您渲染模板的一部分,将其外包在单独的文件中并将已呈现的HTML发送到您的客户端。

因此,您可以使用include模板标记将表模板移动到单独的文件中。 对于AJAX调用,您应该使用第二个视图,它只是呈现模板的表格部分。

所有这些对我来说都是一种hacky,但它应该有效。